[ACCEPTED]-Does GCC have a built-in compile time assert?-static-assert
If you need to use a GCC
version which does 8 not support static_assert
you can use:
#include <boost/static_assert.hpp>
BOOST_STATIC_ASSERT( /* assertion */ )
Basically, what 7 boost does is this:
Declare (but don't define!) a
template< bool Condition > struct STATIC_ASSERTION_FAILURE;
Define 6 a specialization for the case that the assertion 5 holds:
template <> struct STATIC_ASSERTION_FAILURE< true > {};
Then you can define STATIC_ASSERT 4 like this:
#define STATIC_ASSERT(Condition) \
enum { dummy = sizeof(STATIC_ASSERTION_FAILURE< (bool)(Condition) > ) }
The trick is that if Condition 3 is false the compiler needs to instantiate 2 the struct
STATIC_ASSERTION_FAILURE< false >
in order to compute its size, and 1 this fails since it is not defined.
The following code works as expected with 2 g++ 4.4.0 when compiled with the -std=c++0x
flag:
int main() {
static_assert( false, "that was false" );
}
it 1 displays:
x.cpp: In function 'int main()':
x.cpp:2: error: static assertion failed: "that was false"
If you have an older gcc or use an older 2 C++ standard, or use C, then you can emulate 1 static_assert as described here: http://www.pixelbeat.org/programming/gcc/static_assert.html
This doesn't really answer the question, but 3 I like compile-time asserts based on switch-case 2 better, e.g.
#define COMPILE_TIME_ASSERT(cond) do { switch(0) { case 0: case cond: ; } } while (0)
Works also in C and not only 1 in C++.
NSPR does:
#define PR_STATIC_ASSERT(condition) \
extern void pr_static_assert(int arg[(condition) ? 1 : -1])
which fails if condition
is false because 1 it declares an array of negative length.
you can always play around with templates 4 and non-existant strutures via template-specialization. This 3 is how boost does it as far as I know. This 2 is what I use as a static_assert, it's pretty 1 straight forward.
namespace Internal
{
template<bool x> struct SASSERT_F;
template< > struct SASSERT_F <true> {};
template<int x> struct SASSERT_P {};
#define STATIC_ASSERT(B) \
typedef Internal::SASSERT_P <( \
sizeof (Internal::SASSERT_F <( \
((B)? true : false)) >) \
)> \
StaticAssert##__LINE__ ()
}
Example Of Use
int main(int argc, char **argv)
{
static_assert(sizeof(int) == 1) // Error
static_assert(sizeof(int) == sizeof(int)) // OK
}
Both
BOOST_STATIC_ASSERT(x)
BOOST_STATIC_ASSERT_MSG(x, msg)
will use the C++11 static_assert if 1 your compiler supports it
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.