On this page
  1. constexpr & consteval
  2. Overview
  3. Usage
  4. Notes

constexpr & consteval

Prev: auto | Up: builtins | Next: References & Rvalues
Rel: Templates, sizeof & alignof
Ref: cppreference — constexpr | cppreference — consteval
Tags: #public #prog #cpp #builtins #tier/core


Overview

constexpr allows variables, functions, and constructors to be evaluated at compile time (while still callable at runtime if given runtime arguments). consteval (C++20) defines an immediate function that must be evaluated at compile time—failing compilation otherwise.

Usage

constexpr int square(int x) { return x * x; }
consteval int must_compile_time(int x) { return x * 2; }

constexpr int a = square(8);            // computed at compile time (64)
constexpr int b = must_compile_time(5); // guaranteed compile time (10)

// Compile-time branch elimination (C++17)
template <typename T>
auto stringify(const T& v) {
    if constexpr (sizeof(T) <= 4) {
        return static_cast<long>(v);
    } else {
        return v;
    }
}

Notes

Linked from

Related notes