Does GCC have a built-in compile time assert?
If you have an older gcc or use an older C++ standard, or use C, then you can emulate static_assert as described here: http://www.pixelbeat.org/programming/gcc/static_assert.html
If you need to use a GCC
version which does not support static_assert
you can use:
#include <boost/static_assert.hpp>
BOOST_STATIC_ASSERT( /* assertion */ )
Basically, what boost does is this:
Declare (but don't define!) a
template< bool Condition > struct STATIC_ASSERTION_FAILURE;
Define a specialization for the case that the assertion holds:
template <> struct STATIC_ASSERTION_FAILURE< true > {};
Then you can define STATIC_ASSERT like this:
#define STATIC_ASSERT(Condition) \
enum { dummy = sizeof(STATIC_ASSERTION_FAILURE< (bool)(Condition) > ) }
The trick is that if Condition is false the compiler needs to instantiate the struct
STATIC_ASSERTION_FAILURE< false >
in order to compute its size, and this fails since it is not defined.
According to this page, gcc has had static_assert
since 4.3.
The following code works as expected with g++ 4.4.0 when compiled with the -std=c++0x
flag:
int main() {
static_assert( false, "that was false" );
}
it displays:
x.cpp: In function 'int main()':
x.cpp:2: error: static assertion failed: "that was false"