Our existing compile-time assert implementation is based on negative array index, and it provides poor diagnostic output on GCC. C++0x's static_assert
is a very nice feature, and the diagnostic output it provides is much better. I know GCC has already implemented some C++0x features. Does anyone know if static_assert
is among them and if it is then since what GCC version?
assert(f != must be done at run time. However, an assertion that tests the value of a constant expression, such as the size or offset of a structure member, can be done at compile time.
It is available in the C11 version of C. static_assert is used to ensure that a condition is true when the code is compiled.
Of course, the expression in static assertion has to be a compile-time constant. It can't be a run-time value. For run-time values you have no other choice but use the ordinary assert .
What is static assertion? Static assertions are a way to check if a condition is true when the code is compiled. If it isn't, the compiler is required to issue an error message and stop the compiling process. The condition that needs to be checked is a constant expression. Performs compile-time assertion checking.
According to this page, gcc has had static_assert
since 4.3.
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.
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