From cppreference.com
consteval - specifies that a function is an immediate function, that is, every call to the function must produce a compile-time constant
Explanation
The consteval specifier declares a function or function template to be an immediate function, that is, every
call to the function must (directly or indirectly) produce a compile time
.
An immediate function is a
, subject to its requirements as the case may be. Same as constexpr, a consteval specifier implies inline. However, it may not be applied to destructors, allocation functions, or deallocation functions.
A function or function template declaration specifying consteval may not also specify constexpr, and any redeclarations of that function or function template must also specify consteval.
A
invocation of an immediate function whose innermost non-block scope is not a
of an immediate function or the true-branch of a
(since C++23) must produce a constant expression; such an invocation is known as an immediate invocation.
constevalintsqr(intn){returnn*n;}constexprintr=sqr(100);// OKintx=100;intr2=sqr(x);// Error: Call does not produce a constantconstevalintsqrsqr(intn){returnsqr(sqr(n));// Not a constant expression at this point, but OK}constexprintdblsqr(intn){return2*sqr(n);// Error: Enclosing function is not consteval// and sqr(n) is not a constant}An immediate function may only be named within a subexpression of an immediate invocation or within an immediate function context (i.e. a context mentioned above, in which a call to an immediate function needs not to be a constant expression). A pointer or reference to an immediate function can be taken but cannot escape constant expression evaluation:
constevalintf(){return42;}constevalautog(){return&f;}constevalinth(int(*p)()=g()){returnp();}constexprintr=h();// OKconstexprautoe=g();// ill-formed: a pointer to an immediate function is// not a permitted result of a constant expressionNotes
Feature-test macro ValueStdFeature
(C++20)Immediate functions
(C++23)
(DR20)Making consteval propagate up Keywords
Example
Run this code
#include<iostream>// This function might be evaluated at compile-time, if the input// is known at compile-time. Otherwise, it is executed at run-time.constexprunsignedfactorial(unsignedn){returnn<2?1:n*factorial(n-1);}// With consteval we enforce that the function will be evaluated at compile-time.constevalunsignedcombination(unsignedm,unsignedn){returnfactorial(n)/factorial(m)/factorial(n-m);}static_assert(factorial(6)==720);static_assert(combination(4,8)==70);intmain(intargc,constchar*[]){constexprunsignedx{factorial(4)};std::cout<<x<<'\n';[[maybe_unused]]unsignedy=factorial(argc);// OK// unsigned z = combination(argc, 7); // error: 'argc' is not a constant expression}Output:
24 See also