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.
You can declare static assertions anywhere that you use a using declaration, including namespace scope, block scope, and class member declaration lists.
The declaration of static assertions does not declare a new type or object, and does not imply any size or time cost at run time.
The C++ programming language also supports the _Static_assert keyword in all language levels for improved compatibility with the C programming language.
static_assert(sizeof(long) >= 8, "64-bit code generation not
enabled/supported.");
#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;
}
The following example demonstrates the use of a static_assert declaration in block scope, with templates:
template <typename T, int N> void f() { static_assert (N >=0, "length of array a is negative."); T a[N]; // ... } int main() { f<int, -1>(); }
static_assert(1 / 0, "never shows up!");
When
you compile this program, the compiler does not show the string
literal in the static_assert declaration. Instead,
the compiler issues an error message indicating that the divisor cannot
be zero.