Reputation: 24150
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?
Upvotes: 5
Views: 512
Reputation: 1072
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
Upvotes: 1
Reputation: 71008
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.
Upvotes: 1
Reputation: 881595
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.
Upvotes: 0
Reputation: 490108
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.
Upvotes: 6
Reputation: 355049
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.
Upvotes: 10