gpt4 book ai didi

c++ - constexpr 中的字节顺序

转载 作者:IT老高 更新时间:2023-10-28 22:39:25 25 4
gpt4 key购买 nike

我想创建一个返回系统字节序的 constexpr 函数,如下所示:

constexpr bool IsBigEndian()
{
constexpr int32_t one = 1;
return (reinterpret_cast<const int8_t&>(one) == 0);
}

现在,由于函数将在编译时而不是在实际的目标机器上执行,C++ 规范提供什么保证来确保返回正确的结果?

最佳答案

没有。事实上,这个程序是错误的。来自 [expr.const]:

A conditional-expression e is a core constant expression unless the evaluation of e, following the rules of the abstract machine (1.9), would evaluate one of the following expressions:
— [...]
— a reinterpret_cast.
— [...]

并且,来自 [dcl.constexpr]:

For a constexpr function or constexpr constructor that is neither defaulted nor a template, if no argument values exist such that an invocation of the function or constructor could be an evaluated subexpression of a core constant expression (5.20), or, for a constructor, a constant initializer for some object (3.6.2), the program is ill-formed; no diagnostic required.


这样做的方法只是希望您的编译器足够好,可以为您的机器的字节序提供宏。例如,在 gcc 上,我可以使用 __BYTE_ORDER__ :

constexpr bool IsBigEndian() {
#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
return false;
#else
return true;
#endif
}

关于c++ - constexpr 中的字节顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37866375/

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