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

标签 c++ c++11 constexpr

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

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/

相关文章:

c++ - async_pipe 子进程上的 async_read 不提供任何数据

c++ - 围绕 main 的隐式 try {} catch

c++ - std::function - 值与引用参数

c++ - 为什么允许某些非常量表达式作为 constexpr 逗号运算符的操作数?

constexpr 函数中存在 C++ Wconversion 警告,但模板中没有

c++ - 具有多重循环包含的命名空间

c++ - boost:tcp 客户端的 readline

c++ - 多态结构声明

c++11 - 预期类型说明符 C++ 模板类

c++ - 模板参数函数是否必须被视为潜在的 constexpr?