static_assert declaration (C++0x)

Note: C++0x is a new version of the C++ programming language standard. This is a draft standard and has not been officially adopted in its entirety. The implementation of C++0x is based on IBM's interpretation of the draft C++0x standard and is subject to change at any time without notice. IBM makes no attempt to maintain compatibility with earlier releases and therefore the C++0x language extension should not be relied on as a stable programming interface.

In C++0x, static assertions can be declared to detect and diagnose common usage errors at compile time.

A static_assert declaration takes the following form:
Read syntax diagramSkip visual syntax diagram
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.

The addition of static assertions to the C++ language has the following benefits: You can use a static_assert declaration to check important program invariants at compile time.

Examples: static_assert declaration

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.