We use the consteval
specifier in C++ to declare an immediate function. An immediate function is a function that must be evaluated at the compile-time to produce a constant. In other words, an immediate function is executed at compile-time.
The constexpr
specifier is the same as the consteval
specfier, except for the fact that if a function declared with consteval
does not return a compile-time constant, the function returns an error.
We can declare an immediate function with the consteval
specifier as shown below:
consteval returnType funcName (parameters)
{
//function body
}
returnType
: The return type of the immediate function.funcName
: The function identifier of the immediate function.parameters
: The input parameters of the immediate function.Consider the code snippet below, which demonstrates the use of the consteval
specifier:
#include <iostream>consteval int add(int a, int b) {return a + b;}int main() {std::cout << "sum(2 + 5)= " << add(2, 5) << std::endl;const int a = 2;const int b = 5;std::cout << "sum(2 + 5)= " << add(a, b) << std::endl;int a2 = 2;int b2 = 5;//std::cout << "sum(2 + 5)= " << add(a2, b2) << std::endl; //Error: Call does not produce a constantreturn 0;}
sum(2 + 5)= 7
sum(2 + 5)= 7
An immediate function add
is declared in line 3 using the consteval
specifier.
2
and 5
are passed to the immediate function add
. It is a valid invocation, so the function returns the answer.a
and b
, are passed to the immediate function add
. It is a valid invocation, so the function returns the answer.a2
and b2
are not constant expressions. Thus, the invocation of the immediate function is not valid and the function returns an error.Free Resources