Modern C++ › C++11
constexpr, static_assert and decltype
Compile-time evaluation and checking.
Explanation
constexpr marks a variable or function as usable in constant expressions: the compiler may evaluate it at compile time, and must when the result is needed as a constant (array bound, template argument, static_assert). It replaces many macros and template-metaprogramming tricks.
- A
constexprvariable is implicitlyconstand must have a constant initializer. - In C++11 a
constexprfunction is restricted to a singlereturnstatement (recursion and?:instead of loops); C++14 relaxes this to loops and locals. - A
constexprfunction called with runtime arguments just runs at run time. - A
constexprconstructor makes user-defined literal types.
static_assert(condition, "message") checks a condition at compile time and aborts compilation with the message if it is false.
decltype(expr) yields the exact type of an expression without evaluating it; useful in templates and for return types.
Example
#include <iostream>
#include <type_traits>
constexpr int square(int x) { return x * x; }
constexpr int factorial(int n) { // C++11 style: recursion + ?:
return n <= 1 ? 1 : n * factorial(n - 1);
}
struct Point {
int x, y;
constexpr Point(int x_, int y_) : x(x_), y(y_) {}
constexpr int manhattan() const { return (x < 0 ? -x : x) + (y < 0 ? -y : y); }
};
template <typename T>
auto add(T a, T b) -> decltype(a + b) { return a + b; } // trailing return type
int main() {
constexpr int n = factorial(5); // evaluated by the compiler
int table[square(4)]; // array size must be a constant: 16
static_assert(n == 120, "factorial is broken");
static_assert(sizeof(int) >= 4, "need at least 32-bit int");
static_assert(std::is_integral<decltype(n)>::value, "n must be integral");
constexpr Point p(3, -4);
static_assert(p.manhattan() == 7, "manhattan");
int runtime = 6;
std::cout << factorial(runtime) << " " << n << " " << sizeof(table) / sizeof(table[0])
<< " " << add(1.5, 2.0) << "\n"; // still fine with runtime args
decltype(n) copy = n; // const int
(void)copy;
return 0;
}
Common pitfalls
constexprdoes not guarantee compile-time evaluation; force it by using the result in a constant context or aconstexprvariable (C++20constevalguarantees it).- A
constexprfunction body that calls a non-constexprfunction (or usesnew,goto,tryin C++11) fails to compile when a constant is required. - Deep recursion in
constexprhits the compiler’s evaluation limit. decltype((x))(double parentheses) is a reference type, whiledecltype(x)is the declared type ofx.static_assertneeds a constant condition; it can’t test runtime values.
Legacy vs modern
C++98 used const for simple constants, macros, enum { N = 4 } hacks, and template metaprogramming (Factorial<5>::value) for compile-time computation. C++14 relaxes constexpr functions (loops, locals), C++17 adds if constexpr and constexpr lambdas, C++20 adds consteval, constinit and allocation in constexpr code. C++17 lets static_assert omit the message.
Exercises
1. Write a constexpr function power(base, exp) in C++11 style.
constexpr int power(int b, int e) { return e == 0 ? 1 : b * power(b, e - 1); }