Skip to content
Quantoros

How has constexpr expanded across C++14, 17, 20, and 23?

C++Level: IntermediateCompile-Time Programming

How has constexpr expanded across C++14, 17, 20, and 23?

Hints
  • Identify types, object lifetimes and compile-time decisions.
  • Separate language guarantees from a particular compiler's behavior.

Answer

constexpr Evolution by Standard

C++11:

  • Introduced constexpr for simple functions (single return statement)
  • constexpr variables must be initialized with constant expressions

C++14:

  • constexpr functions can have multiple statements, loops, and local variables
  • constexpr member functions are no longer implicitly const

C++17:

  • if constexpr for compile-time conditional compilation
  • constexpr lambdas

C++20:

  • consteval for immediate functions (must evaluate at compile time)
  • constinit for compile-time initialization of non-const variables
  • constexpr virtual functions
  • constexpr dynamic allocation (new/delete) within constant expressions
  • constexpr std::vector and std::string

C++23:

  • if consteval for detecting constant evaluation context
  • Relaxed constexpr restrictions on non-literal types

Answer section

Source and licence: C/C++ Interview Cheatsheet — Chang Ning Tsai · MIT

Related questions