constexpr specifier (C++11 feature)

From Cppreference

Jump to: navigation, search
  • constexpr - specifies that the value of a variable or function can be computed at compile time

[edit] Explanation

constexpr specifier declares that it is possible to evaluate the value of the function or variable at compile time, they then can be used where only compile time constants are allowed. constexpr implies const.

constexpr variables must satisfy the following requirements:

  • it must be immediately constructed or assigned a value.
  • the constructor parameters or the value to be assigned must contain only literal values, constexpr variables and functions.
  • the constructor used to construct the object (either implicit or explicit) must satisfy the requirements of constexpr constructor. In the case of explicit constructor, it must have constexpr specified.

constexpr functions must satisfy the following requirements:

  • it must not be virtual
  • its return type must be literal type
  • each of its parameters must be literal types
  • the function body must be either deleted or defaulted or contain only the following:
  • null statements
  • static_assert declarations
  • typedef declarations and alias declarations that do not define classes or enumerations
  • using declarations
  • using directives
  • exactly one return statement that contains only literal values, constexpr variables and functions.

constexpr constructor must satisfy the following requirements:

[edit] Keywords

constexpr

[edit] Example