if consteval检测是否constexpr在常量表达式上下文中调用函数。该提案的动机是针对打算consteval从constexpr函数调用函数的情况进行介绍。为了理解这意味着什么,我们考虑以下示例。
假设我们有一个consteval函数f:
consteval int f( int i )
{ ... }
Run Code Online (Sandbox Code Playgroud)
f只能在常量表达式中调用。另一方面,constexpr函数g可以在常量表达式中或在运行时调用。这取决于参数g在编译时是否已知。现在,f从编译时调用的gifg调用可以按如下方式完成。
constexpr int g( int i )
{
if consteval { //1
return f( i );
}
else {
return fallback();
}
}
Run Code Online (Sandbox Code Playgroud)
这里if constevalin line//1触发器 ifg在常量表达式中调用。注意 中不能有条件//1。后面的大括号if consteval也是强制性的。
引入 C++20is_constant_evaluated用于检测函数调用是否发生在常量计算上下文中。is_constant_evaluated在我们的示例中使用会导致一个微妙的错误。即//1按if constexpr (std::is_constant_evaluated()) {结果交换is_constant_evaluated总是返回true。