C++ constexpr函数中的非文本(通过std::is_constant_求值)

C++ constexpr函数中的非文本(通过std::is_constant_求值),c++,constexpr,c++20,C++,Constexpr,C++20,在constexpr函数中,如果语句受C++20的std::is_constant_evaluated()约束,我无法在的分支中定义非文字变量?Clang和GCC都表明它是不允许的,但在下面的示例中,其他不能在编译时进行计算的构造是允许的。对非文字的使用是否有具体限制 #include <type_traits> struct Foo { ~Foo() {} }; void non_constexpr() {} constexpr bool bar() { if (st

constexpr
函数中,如果
语句受C++20的
std::is_constant_evaluated()
约束,我无法在
的分支中定义非文字变量?Clang和GCC都表明它是不允许的,但在下面的示例中,其他不能在编译时进行计算的构造是允许的。对非文字的使用是否有具体限制

#include <type_traits>

struct Foo {
  ~Foo() {}
};

void non_constexpr() {}

constexpr bool bar()
{
  if (std::is_constant_evaluated()) {
  } else {
    non_constexpr();
    double d;
    reinterpret_cast<int*>(&d);
    Foo f;  // error: variable ‘f’ of non-literal type ‘Foo’ in ‘constexpr’ function
  }

  return true;
}

constexpr bool x = bar();
#包括
结构Foo{
~Foo(){}
};
void non_constexpr(){}
constexpr bool bar()
{
if(std::is_constant_evaluated()){
}否则{
non_constexpr();
双d;
重新解释铸造(d);
Foo f;//错误:“constexpr”函数中非文字类型“Foo”的变量“f”
}
返回true;
}
constexpr bool x=bar();

有一个特定的限制。在这种情况下,对
constexpr
函数体的结构限制

[dcl.constexpr]

constexpr函数的定义应满足 以下要求:

  • 其功能体不得封闭
    • 非文字类型变量或静态或线程存储持续时间变量的定义
这就是长话短说。如果您想知道为什么会这样,因为在常量求值中不会执行任何禁止的代码,这也是一个问题。不幸的是,我现在还不知道答案。这可能只是一些没有人想过要改变的事情