Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compile-time assertions in C++?

Tags:

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 - 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?

like image 439
Jake Petroules Avatar asked Aug 14 '10 02:08

Jake Petroules


1 Answers

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.

like image 121
James McNellis Avatar answered Oct 07 '22 18:10

James McNellis