consteval: Run C++ Code At Compile Time Only#
Why?#
constexprhas a “maybe” attached to itEvaluation in
constexprcontext must be forced (see for example here)constexpr int i = f(); // <-- force compiletime evaluation of f
Moreover:
iis a constantSomething different is needed: a function that
Always evaluates at compiletime (⟶ no forcing needed)
Value can be assigned to non-
constvariable
⟶
constevalOnly available at compiletime
Usage: At Compiletime Only#
Can only be used in
constexprcontext⟶ 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
constexprcontext⟶ no forcing needed
⟶ assigned-to variable can be mutable
And constexpr?#
constevalfunction can useconstexprfunctionsReason:
constevalruns at compiletime only, so it uses the compiletime version of the calledconstexprfunctions
#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;
}