constexpr specifier (since C++11)
constexpr
- specifies that the value of a variable or function can appear in constant expressions
Explanation
The constexpr
specifier declares that it is possible to evaluate the value of the function or variable at compile time. Such variables and functions can then be used where only compile time constant expressions are allowed (provided that appropriate function arguments are given). A constexpr specifier used in an object declaration implies const. A constexpr specifier used in a function or static member variable (since C++17) declaration implies inline.
A constexpr variable must satisfy the following requirements:
- its type must be a
LiteralType
. - it must be immediately initialized
- the full-expression of its initialization, including all implicit conversions, constructors calls, etc, must be a constant expression
- its type must be a
A constexpr function must satisfy the following requirements:
- it must not be virtual
- its return type must be
LiteralType
- each of its parameters must be
LiteralType
- there exists at least one set of argument values such that an invocation of the function could be an evaluated subexpression of a core constant expression (for constructors, use in a constant initializer is sufficient) (since C++14). No diagnostic is required for a violation of this bullet.
|
(until C++14) |
|
(since C++14) |
A constexpr constructor must satisfy the following requirements:
- each of its parameters must be
LiteralType
. - the class must have no virtual base classes
- the constructor must not have a function-try-block
- each of its parameters must be
|
(until C++14) |
|
(since C++14) |
For constexpr function templates and constexpr member functions of class templates, at least one specialization must satisfy the abovementioned requirements. Other specializations are still considered as constexpr, even though a call to such a function cannot appear in a constant expression.
Notes
Because the noexcept operator always returns true
for a constant expression, it can be used to check if a particular invocation of a constexpr function takes the constant expression branch:
constexpr int f(); constexpr bool b1 = noexcept(f()); // false, undefined constexpr function constexpr int f() { return 0; } constexpr bool b2 = noexcept(f()); // true, f() is a constant expression
Constexpr constructors are permitted for classes that aren't literal types. For example, the default constructor of std::unique_ptr is constexpr, allowing constant initialization.
Reference variables can be declared constexpr (their initializers have to be reference constant expressions):
static constexpr int const& x = 42; // constexpr reference to a const int object // (the object has static storage duration // due to life extension by a static reference)