In C++0x, static assertions can be declared to detect and diagnose common usage errors at compile time.
static_assert declaration syntax >>-static_assert--(--constant-expression--,--string-literal-----> >--)--;--------------------------------------------------------><
The constant-expression must be a constant expression that can be contextually converted to bool. If the value of the expression converted in such a way is false, the compiler issues a severe error containing the string literal with the source location of the static_assert declaration. Otherwise, the static_assert declaration has no effect.
The static_assert declaration can appear anywhere that a using-declaration can, including namespace scope, block scope, and class member declaration lists.
The static_assert declaration does not declare a new type or object, and does not imply any size or time cost at run time.
static_assert in namespace scope:
static_assert(sizeof(long) >= 8, "64-bit code generation not enabled/supported.");
static_assert in class scope, with templates:
#include <type_traits> #include <string> template<typename T> struct X { static_assert(std::tr1::is_pod<T>::value, "POD required to instantiate class template X."); // ... }; int main() { X<std::string> x; }
static_assert in block scope, with templates:
template <typename T, intN> void f() { static_assert (N >=0, "length of array a is negative."); T a[N]; // ... } int main() { f<int, -1>(); }
An erroneous static_assert with an invalid constant expression:
static_assert(1 / 0, "never shows up!");
When this is compiled, instead of showing the string literal in the static_assert declaration, the compiler issues an error message indicating that the divisor must not be zero.