tags:

views:

1492

answers:

5

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?

+8  A: 

according to this page. gcc has had static_assert since 4.3

Evan Teran
+1 for not using LMGTFY.
Johnsyweb
+5  A: 

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"
anon
+5  A: 

If you need to use a gcc version which does not support it 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.

Tobias
I wonder if there's any way to make a sensible error message appear from a trick like this...
Thomas
According to the documentation (http://www.boost.org/doc/libs/1_43_0/doc/html/boost_staticassert.html), this is one of the goals of Boost.StaticAssert: “One of the aims of BOOST_STATIC_ASSERT is to generate readable error messages. These immediately tell the user that a library is being used in a manner that is not supported.”
Philipp
A: 

This doesn't really answer the question, but I like compile-time asserts based on switch-case better, e.g.

#define COMPILE_TIME_ASSERT(cond) do { switch(0) { case 0: case cond: ; } } while (0)

Works also in C and not only in C++.

laalto
This technique has two shortcomings. First, such assertion can not be used at class or namespace level. And second, when assertion is successfull, it generates executable code, inflating the binary. It is left to your optimizing compiler to remove it, and that is not guaranteed. :-(
VladLosev
+1  A: 

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

pixelbeat