gpt4 book ai didi

c++ - constexpr 函数内的非文字(通过 std::is_constant_evaluated)

转载 作者:行者123 更新时间:2023-12-01 14:20:08 25 4
gpt4 key购买 nike

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

最佳答案

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

[dcl.constexpr]

3 The definition of a constexpr function shall satisfy thefollowing requirements:

  • its function-body shall not enclose
    • a definition of a variable of non-literal type or of static or thread storage duration.

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

关于c++ - constexpr 函数内的非文字(通过 std::is_constant_evaluated),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62873895/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com