consteval
: Run C++ Code At Compile Time Only#
Why?#
constexpr
has a “maybe” attached to itEvaluation in
constexpr
context must be forced (see for example here)constexpr int i = f(); // <-- force compiletime evaluation of f
Moreover:
i
is a constantSomething different is needed: a function that
Always evaluates at compiletime (⟶ no forcing needed)
Value can be assigned to non-
const
variable
⟶
consteval
Only available at compiletime
Usage: At Compiletime Only#
Can only be used in
constexpr
context⟶ parameters must be known at compiletime
#include <iostream>
consteval int add(int l, int r)
{
return l+r;
}
int main()
{
const int a=40, b=2;
int answer = add(a, b); // <-- no need to force
std::cout << answer << '\n';
return 0;
}
Not ok: mutable parameters
#include <iostream>
consteval int add(int l, int r)
{
return l+r;
}
int main()
{
int a=40, b=2;
int answer = add(a, b); // <-- ERROR: is not usable in a constant expression
std::cout << answer << '\n';
return 0;
}
No Forcing Needed ⟶ Can Assign To Mutable Variables#
Always runs in
constexpr
context⟶ no forcing needed
⟶ assigned-to variable can be mutable
And constexpr
?#
consteval
function can useconstexpr
functionsReason:
consteval
runs at compiletime only, so it uses the compiletime version of the calledconstexpr
functions
#include <iostream>
constexpr int add(int l, int r)
{
return l+r;
}
consteval int add3(int v1, int v2, int v3)
{
return add(v1, add(v2, v3));
}
int main()
{
const int a=40, b=2;
int answer = add(a, b);
std::cout << answer << '\n';
return 0;
}