如果 consteval 需要什么?

Cla*_*tus 5 c++ constexpr consteval c++23

C++23 将引入if consteval. 这将在哪里使用,它与constexpr if?

Cla*_*tus 8

if consteval检测是否constexpr在常量表达式上下文中调用函数。该提案的动机是针对打算constevalconstexpr函数调用函数的情况进行介绍。为了理解这意味着什么,我们考虑以下示例。

假设我们有一个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在我们的示例中使用会导致一个微妙的错误。即//1if constexpr (std::is_constant_evaluated()) {结果交换is_constant_evaluated总是返回true

  • 问题不在于 `if constexpr (is_constant_evaluate())` 是一个错误(它是,但编译器警告,所以 meh),但即使使用 `if (is_constant_evaluate())` 你也不能调用 `f( i)`那里。 (5认同)
  • 为什么我们不能至少做到这一点?constexpr int g( int i ) { if consteval { static_assert( i < ... ); ... } ... } 如果我们知道在编译时会计算某些内容,为什么不相应地处理这些值呢? (2认同)