constexpr & Compile-Time Computation
Prerequisites: Template metaprogramming basics
constexpr marks a function (or variable) that can be
evaluated at compile time, when given compile-time-known inputs —
doing real work before the program even runs, with zero runtime
cost.
constexpr int factorial(int n) {
return n <= 1 ? 1 : n * factorial(n - 1);
}
constexpr int result = factorial(5); // computed at COMPILE time
int n = getUserInput();
int runtimeResult = factorial(n); // same function, now at RUNTIME
The same constexpr function works both ways — the compiler
evaluates it at compile time whenever it can prove the inputs are
known that early, and falls back to ordinary runtime execution
otherwise. This is the modern, far more readable replacement for
most of what template metaprogramming used to be needed for.