Show: Delphi C++
Display Preferences

Static Assertions (C++11)

From RAD Studio
Jump to: navigation, search

Go Up to C++11 Features Index

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

Personal tools
RAD Studio 10.2 Tokyo
In other languages
Previous Versions
Assistance