gpt4 book ai didi

c++ - 在编译时测试字节序 : is this constexpr function correct according to the standard?

转载 作者:IT老高 更新时间:2023-10-28 23:00:28 26 4
gpt4 key购买 nike

在寻找一种在编译时检查字节顺序的方法后,我想出了以下解决方案:

static const int a{1};

constexpr bool is_big_endian()
{
return *((char*)&(a)) == 1;
}

GCC 仅在需要 constexpr 的某些情况下接受此代码:

int b[is_big_endian() ? 12 : 25]; //works
std::array<int, testendian() ? 12 : 25> c; //fails

对于第二种情况,GCC 说 error: access value of 'a' through a 'char' glvalue in a constant expression。我在标准中找不到任何禁止此类事情的内容。也许有人可以澄清在哪种情况下 GCC 是正确的?

最佳答案

这是我从 Clang 3.1 ToT 中得到的:

error: constexpr function never produces a constant expression

§5.19 [expr.const]

p1 Certain contexts require expressions that satisfy additional requirements as detailed in this sub-clause; other contexts have different semantics depending on whether or not an expression satisfies these requirements. Expressions that satisfy these requirements are called constant expressions.

p2 A conditional-expression is a core constant expression unless it involves one of the following as a potentially evaluated subexpression:

  • [...]
  • a reinterpret_cast (5.2.10);

因此,(char*)&(a) 的计算结果为 reinterpret_cast,因此该函数永远不是有效的 constexpr 函数。

关于c++ - 在编译时测试字节序 : is this constexpr function correct according to the standard?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9152580/

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