Programming with constant expressions
An expression prefixed with the constexpr
keyword tells the compiler that the expression should be evaluated at compile time:
constexpr auto v = 43 + 12; // Constant expression
The constexpr
keyword can also be used with functions. In that case, it tells the compiler that a certain function is intended to be evaluated at compile time if all the conditions allowing for compile-time evaluation are fulfilled. Otherwise, it will execute at runtime, like a regular function.
A constexpr
function has a few restrictions; it is not allowed to do the following:
- Handle local static variables
- Handle
thread_local
variables - Call any function, which, in itself, is not a
constexpr
function
With the constexpr
keyword, writing a compile-time evaluated function is as easy as writing a regular function since its parameters are regular parameters instead of template parameters.
Consider the following constexpr
function...