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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With