tags:

views:

124

answers:

5

I recently came upon the need to have compile-time assertions in C++ to check that the sizes of two types were equal.

I found the following macro on the web (stated to have come from the Linux kernel):

#define X_ASSERT(condition) ((void)sizeof(char[1 - 2*!!(condition)]))

which I used like so:

X_ASSERT(sizeof(Botan::byte) != sizeof(char));

This gets me curious - although this works, is there a cleaner way to do so? (obviously there's more than one way, as it is) Are there advantages or disadvantages to certain methods?

+8  A: 

In C++0x, there is a new language feature, static_assert, which provides a standard way to generate compile-time assertions. For example,

static_assert(sizeof(Botan::byte) != 1, "byte type has wrong size");

Visual C++ 2010 supports static_assert, as do g++ 4.3 (and greater) and Intel C++ 11.0.

James McNellis
+6  A: 

You might want to take a look at Boost StaticAssert. The internals aren't exactly clean (or weren't the last time I looked) but at least it's much more recognizable, so most people know what it means. It also goes to some pains to produce more meaningful error messages if memory serves.

Jerry Coffin
I actually prefer [`BOOST_MPL_ASSERT_MSG`](http://www.boost.org/doc/libs/1_43_0/libs/mpl/doc/refmanual/assert-msg.html).
GMan
A: 

There's an excellent #error preprocessor directive (see here for a good essay about it), but I believe it needs to be within a #if as opposed to being used in a "free-standing" as in your example use.

Alex Martelli
`#error` has the disadvantage that it is a preprocessing directive and is evaluated before the source is parsed, and you can't use things like `sizeof` or non-macro constants in the controlling `#if` directive.
James McNellis
+1  A: 

Some other interesting options are here: http://www.jaggersoft.com/pubs/CVu11_3.html

Neat reading as the author walks the C (not C++) spec looking for syntax that can be leveraged as compile-time assertions.

quixoto
+1  A: 

To do it right you need a C++0x friendly compiler, see James McNellis' and Jerry Coffins answers.

You can't do much with the 1998 or 2003 C++ standards. Take a look at these links for examples:

http://en.wikipedia.org/wiki/Assertion_(computing)#Static_assertions http://ksvanhorn.com/Articles/ctassert.html

TerryP