A slightly less banal use of static_assert

22 07 2010

The examples used for demonstrating the use of C++0x‘s static_assert are usually pretty unimaginative, for example MSDN (among many others) uses something along the lines of:

static_assert(sizeof(void *) == 4,
              "64-bit code generation is not supported.");

While preparing a presentation for our group about VC10 I came up with a slightly sexier example (for über nerdy values of sexy).

string to_string(int i)
	char buff[16];
	static_assert(std::numeric_limits::digits10 < _countof(buff) -1,
		 "int won't fit in buffer");

	_itoa_s(i, buff, 10);
	return string(buff);

The cool thing is that VS10 displays compilation errors as design time, this is what it looks like  when I delete the 1 from buff’s size.




Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: