开发者

Compile-time assertions in C++?

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 -开发者_StackOverflow中文版 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.


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.


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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜