Compile-time evaluation using constexpr
The constexpr
function was added in C++11 and enhanced in C++14. Besides the fact that we can declare a variable as constexpr
, it indicates that, where possible, the return value is computed at compile time and is constant. A constexpr
function is one whose return value can be computed at compile time when the consuming code requires it, according to the definition. In our example, the body of the function is written as a single statement because only a very small subset of the language can be used by constexpr
functions. Many constexpr
constraints were removed in C++14, making it much easier to write them now. You have already seen its use in the examples, and now, we will go deeper.
Here’s the syntax of constexpr
:
constexpr literal identity =
expression
constexpr literal
identity {expression};
constexpr literal
identity (parameters);
constexpr
constructor (parameters);
As a constexpr
variable, it must be...