In C++, constexpr
is a feature that allows the evaluation of expressions at compile time. It was introduced in C++11 and has been extended in later versions of the language.
Introduction to constexpr
In C++11, constexpr
was limited to a small subset of operations, and the expressions had to be simple enough to be evaluated at compile time. For example, you could declare a constant value using constexpr
, but it was limited to basic arithmetic and logical operations.
constexpr int square(int x) {
return x * x;
}
C++14 and extended constexpr
With the introduction of C++14, the constexpr
keyword was extended to allow more complex operations, including loops and conditional statements.
constexpr int fibonacci(int n) {
if (n <= 1) {
return n;
} else {
return fibonacci(n - 1) + fibonacci(n - 2);
}
}
In this example, the fibonacci
function can be evaluated at compile time, as long as the input value is known at compile time as well.
C++20 and consteval
C++20 introduced consteval
, which is even more powerful than the extended constexpr
. It guarantees that the function will be evaluated at compile time and can be used for a broader range of computations.
consteval int factorial(int n) {
int result = 1;
for (int i = 1; i <= n; ++i) {
result *= i;
}
return result;
}
In this example, the factorial
function is guaranteed to be evaluated at compile time, providing a more flexible and powerful way to perform computations during compilation.
Conclusion
constexpr
in C++ has evolved significantly since its introduction in C++11. With the extensions introduced in C++14 and the addition of consteval
in C++20, the language now provides more flexibility and power for compile-time computation, enabling more complex operations to be performed at compile time.
References:
- C++ reference: Constexpr specifier
- Modern C++ features: Constexpr – a mighty beast with superpowers