Analog literals

May 20, 2009 [C++, Tech]

I love this: C++ Multi-Dimensional Analog Literals.

I quote:

Have you ever felt that integer literals like "4" don't convey the true size of the value they denote? If so, use an analog integer literal instead:

unsigned int b = I---------I;

It goes on to explain that you can use 2- and 3-dimensional "analog literals". Genius. Read the article. Try to read the code :)

Isn't C++ ... erm ... powerful?

You'll notice that there are 9 dashes used to denote 4. This is because the trick it is using uses operator--. I'm sure the original author did this in his/her sleep and thought it was too trivial to post (or posted it before?) but I thought: if we can use operator! instead, can't we create analog literals that use the same number of symbols as the number we want?

The answer is yes, and it's pretty simple:

notliterals.h:

class NotLiteral
{
public:
NotLiteral( unsigned int ival )
: val_( ival )
{
}

NotLiteral operator!() const
{
	return NotLiteral( val_ + 1 );
}

operator unsigned int() const
{
	return val_;
}

unsigned int val_;

};

const NotLiteral NL( 0 );

test_notliterals.cpp:

#include "notliterals.h"
#include <cassert>

int main() { assert( !!!!NL == 4 ); assert( !!NL == 2 );

assert( !!!!!!!!!!!!!!!NL == 15 );

}

With this simpler form, it's almost believable that there might be some kind of useful application?

Extending this to 3 dimensions is left as an exercise for the reader. For 2 dimensions, if you just want the area (not the width and height), how about this?:

	assert( !!!
	        !!!
	        !!!NL == 9 );

Update: By the way, if you don't like all the emphasis! of! using! exclamation! marks! you can do the same thing with the unary one's complement operator, ~. Just replace "!" everywhere above with "~" and you're done. Unfortunately, you can't do the same with - or + because the parser recognises "--" as the decrement operator instead of seeing that it is clearly two calls to the unary negation operator.