The constexpr keyword
The constexpr
keyword 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:
- Allocate memory on the heap
- Throw exceptions
- Handle local static variables
- Handle
thread_local
variables - Call any function, which, in itself, is not a constexpr.
Note
Back in C++11, constexpr
functions were only allowed to contain a single return statement, requiring the programmer to resort to recursion for more advanced constexpr
functions; however, in C++14 this restriction has been removed. The constexpr
functions may now contain several statements, declare variables, and even mutate variables.
With the constexpr keyword, writing a compile-time evaluated function is as easy as writing a regular function, as its parameters are regular parameters instead...