`consteval` — C++ Keyword
`consteval` — C++ Keyword
The consteval keyword in C++20: declares an immediate function that must be evaluated at compile time.
`consteval` — C++ Keyword
The consteval keyword in C++20: declares an immediate function that must be evaluated at compile time.
Use reference pages to confirm names, categories, nearby facilities, and the constraints that matter before writing or reviewing code.
constevalDeclares an immediate function: every call to it must produce a compile-time constant. If the call cannot be evaluated at compile time, the program is ill-formed (unlike constexpr, which also allows runtime evaluation). Introduced in C++20.
consteval return-type func(params) { body }
#include <print>
// Must be evaluated at compile time
consteval int square(int n) {
return n * n;
}
constexpr int maybe_ct(int n) {
return n * n; // can be runtime or compile-time
}
int main() {
constexpr int a = square(7); // OK: compile-time
std::println("{}", a); // 49
// int x = 7;
// int b = square(x); // error: x is not a constant expression
int x = 7;
int b = maybe_ct(x); // OK: constexpr allows runtime
std::println("{}", b); // 49
}
consteval for functions like hash seeds, lookup-table generators, or compile-time validators that must never run at runtime.consteval lambdas are also supported in C++20.constevalint main() {
// Pick one facility from this reference page.
// Write the smallest program that exercises its main precondition,
// complexity rule, or lifetime constraint before scaling up.
return 0;
}