Learning Hub Search Ctrl K

Modern C++ › C++11

constexpr, static_assert and decltype

Compile-time evaluation and checking.

Since C++11 intermediate #constexpr#static_assert#decltype#compile-time#type-deduction

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 constexpr variable is implicitly const and must have a constant initializer.
  • In C++11 a constexpr function is restricted to a single return statement (recursion and ?: instead of loops); C++14 relaxes this to loops and locals.
  • A constexpr function called with runtime arguments just runs at run time.
  • A constexpr constructor 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

  • constexpr does not guarantee compile-time evaluation; force it by using the result in a constant context or a constexpr variable (C++20 consteval guarantees it).
  • A constexpr function body that calls a non-constexpr function (or uses new, goto, try in C++11) fails to compile when a constant is required.
  • Deep recursion in constexpr hits the compiler’s evaluation limit.
  • decltype((x)) (double parentheses) is a reference type, while decltype(x) is the declared type of x.
  • static_assert needs 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); }