iam*_*ind 13 c++ endianness compile-time type-punning c++11
我已就此主题提出了很多问题,但到目前为止找不到任何解决方案.这里提到了一个自然的解决方案:在编译时确定字节序.
但是,评论中提到的相关问题和答案相同.
通过一些修改,我能够在-std=c++11没有任何警告的情况下使用g ++和clang ++()编译类似的解决方案.
static_assert(sizeof(char) == 1, "sizeof(char) != 1");
union U1
{
int i;
char c[sizeof(int)];
};
union U2
{
char c[sizeof(int)];
int i;
};
constexpr U1 u1 = {1};
constexpr U2 u2 = {{1}};
constexpr bool IsLittleEndian ()
{
return u1.i == u2.c[0]; // ignore different type comparison
}
static_assert(IsLittleEndian(), "The machine is BIG endian");
Run Code Online (Sandbox Code Playgroud)
演示.
这可以被认为是决定字节序的确定性方法还是错过类型惩罚或其他什么?
std::endian从 C++20 开始,您可以从标头使用<type_traits>:
#include <type_traits>
int main()
{
static_assert(std::endian::native==std::endian::big,
"Not a big endian platform!");
}
Run Code Online (Sandbox Code Playgroud)