constexpr 函数中的非文字(通过 std::is_constant_evaluated)
Non-literal within a constexpr function (via std::is_constant_evaluated)
在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函数的定义应满足 以下要求:
- 其功能体不得封闭
- 非文本类型或静态或线程存储持续时间的变量的定义。
这就是它的长短。如果你想知道为什么会这样,因为在不断的评估中不会执行禁止的代码,这也是一个好问题。不幸的是,我目前不知道答案。这可能只是没有人想过要改变的事情。
相关文章:
- Why is UINT32_MAX + 1 = 0?
- C++错误:"error: int aaa::bbb is protected within this context"
- 创建具有 new in 函数和"this is nullptr"异常的对象
- 为什么static_assert错误:即使我传递常量"expression must have a constant value"?
- 使用 cmake 的 Linux 终端上的"Conversion to non-scalar type is requested"错误
- Is !NaN not a NaN?
- Directx 11 - CompileFromFile() is not compiling
- Centos7 g++ "to_string is not in a member of std"
- "Unable to start debugging. No process is associated with this object." - 在Visual Studio Code中使用GDB
- Where is std::hardware_destructive_interference_size?
- 将成员函数作为构造函数参数调用时出错 "Variable is not a type name"
- 如何修复 eigen3 中的'non-type template argument is not a constant expression'?
- 如何修复此错误"the value of 'x1' is not usable in a constant expression"?static_assert
- 使用多个文件时"array bound is not an integer constant before ']' token"
- 检查布尔模板参数时摆脱"conditional expression is constant"警告的方法?
- constexpr with std::array - "Non-type template argument is not a constant expression"
- " a variable that can be easily mistaken for a constant variable but is in fact a non-constant varia
- 如何避免模板代码中编译时常量条件"conditional expression is constant"警告?
- 获取错误"array bound is not an integer constant before ']' token"
- 在运行时创建结构时"array bound is not an integer constant"