The constexpr
keyword was introduced in C++11 and enhanced in C++14 and C++17. It enables computations to be performed at compile time.
A constexpr
function can be evaluated at compile time if its arguments are compile-time constants:
constexpr int square(int x) {
return x * x;
}
// Used at compile time
constexpr int result = square(5); // Computed during compilation
// Used at runtime
int input;
std::cin >> input;
int dynamic_result = square(input); // Computed at runtime
While template metaprogramming also enables compile-time computation, constexpr
provides a more readable and maintainable approach:
// Fibonacci with constexpr (C++14 and later)
constexpr int fibonacci(int n) {
if (n <= 1) return n;
return fibonacci(n-1) + fibonacci(n-2);
}
// Usage
constexpr int fib10 = fibonacci(10); // Computed at compile time
The advantage of constexpr
over template metaprogramming is that it uses familiar function syntax rather than recursive template instantiations, making the code easier to understand and maintain.