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
constexprfor simple functions (single return statement) constexprvariables must be initialized with constant expressions
C++14:
constexprfunctions can have multiple statements, loops, and local variablesconstexprmember functions are no longer implicitlyconst
C++17:
if constexprfor compile-time conditional compilationconstexprlambdas
C++20:
constevalfor immediate functions (must evaluate at compile time)constinitfor compile-time initialization of non-const variablesconstexprvirtual functionsconstexprdynamic allocation (new/delete) within constant expressionsconstexprstd::vectorandstd::string
C++23:
if constevalfor detecting constant evaluation context- Relaxed
constexprrestrictions on non-literal types
Source and licence: C/C++ Interview Cheatsheet — Chang Ning Tsai · MIT