Static Assertions (C++11)

From RAD Studio
Jump to: navigation, search

Go Up to C++11 Features in the Classic Compiler

Attention: This page refers to a C++11 feature in the Classic compiler. The Classic compiler is not recommended: instead it is recommend you use the Clang-enhanced compilers, which support modern C++ including C++11, C++14 and C++17.

The static_assert keyword is used to test assertions at compile time. This is one of the C++11 features added to BCC32.

This keyword operates differently than the macro assert, which raises assertions at run time. The keyword static_assert also differs from the preprocessor directive #error, which operates during preprocessing and simply emits a message.

Syntax

A static assertion's declaration is:

static_assert (constant-expression, error-message);

The constant-expression must be one that can be statically evaluated as a boolean. If constant-expression is true, the statement does nothing. If false, the compiler generates an error with the text error-message.

Because the assertion is tested at compile time, static_assert can do error checking in templates. For instance:

template <class T>
   T Test(T x, T y) 
  {
   static_assert(sizeof T <= sizeof long, "Type is too large");
   ...
   };

static_assert is useful for static type checking. A certain function might fail if the implementation of an int is too small, so static_assert has utility outside of templates.

See Also