C++20 `consteval` | Immediate Functions and Compile-Time-Only Evaluation

C++20 `consteval` | Immediate Functions and Compile-Time-Only Evaluation

이 글의 핵심

`consteval` marks immediate functions that must be evaluated at compile time—closing the gap when `constexpr` is too permissive.

Why consteval exists

constexpr functions may run at compile time or runtime. When you need to forbid runtime calls, consteval (C++20) provides compile-time-only immediate functions.

flowchart TD
    subgraph constexpr["constexpr"]
        ce1["Compile-time OK"]
        ce2["Runtime OK"]
    end
    subgraph consteval["consteval"]
        cv1["Compile-time OK"]
        cv2["Runtime error"]
    end

constexpr vs consteval

constexprconsteval
Compile-timeAllowedRequired
RuntimeAllowedNot allowed
UseFlexible utilitiesHard compile-time-only APIs

Immediate functions

consteval functions must be invoked in constant evaluation when used as constant expressions; details follow the standard’s rules for immediate functions.

Note: You generally cannot call consteval from a constexpr function that might run at runtime—use consteval callers or std::is_constant_evaluated()-style branching where appropriate.

Practical uses

  • Range checks that throw at compile time
  • Compile-time string hashing into enums
  • Small consteval validation helpers
  • Configuration tables computed entirely at build time

Common errors

  • Passing runtime values → hard error: not a constant expression.
  • Side effects (I/O, volatile reads, etc.) in consteval bodies—disallowed in constant evaluation.

Production patterns

Compile-time identifier validation, CRC tables, build-mode-dependent pool sizes—same as the Korean article’s code samples.

FAQ

Compiler support: GCC 10+, Clang 10+, MSVC 19.10+ (check your exact minor for full conformance).

Resources: cppreference — consteval, C++20 — The Complete Guide.


  • static_assert
  • C++20 Concepts

Keywords

C++, consteval, C++20, compile-time, constexpr, metaprogramming.

See also

  • constexpr functions