constexpr 函数中的非文字(通过 std::is_constant_evaluated)

Non-literal within a constexpr function (via std::is_constant_evaluated)

本文关键字:is constant evaluated std 通过 函数 文字 constexpr      更新时间:2023-10-16

constexpr函数中,我无法在以 C++20std::is_constant_evaluated()为条件的if语句的分支中定义非文字变量?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();

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

[dcl.constexpr]

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

  • 其功能体不得封闭
    • 非文本类型或静态或线程存储持续时间的变量的定义。

这就是它的长短。如果你想知道为什么会这样,因为在不断的评估中不会执行禁止的代码,这也是一个好问题。不幸的是,我目前不知道答案。这可能只是没有人想过要改变的事情。