使用C ++ 11在编译时以编程方式查找字节序 [英] Finding endian-ness programmatically at compile-time using C++11
问题描述
我已经在SO中提到了有关此主题的许多问题,但到目前为止找不到任何解决方案.这里提到了一种自然的解决方案:在编译时确定字节序.
但是,评论和评论中提到的相关问题.相同的答案.
I have referred many questions in SO on this topic, but couldn't find any solution so far. One natural solution was mentioned here: Determining endianness at compile time.
However, the related problems mentioned in the comments & the same answer.
通过一些修改,我可以使用g ++& clang ++(-std=c++11
),没有任何警告.
With some modifications, I am able to compile a similar solution with g++ & clang++ (-std=c++11
) without any warning.
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");
演示.
这可以被认为是确定字节序的确定性方法吗,或者它会错过类型拼写或其他东西?
Can this be considered a deterministic method to decide the endian-ness or does it miss type-punning or something else?
推荐答案
自C ++ 20起,您可以使用<type_traits>标头中的"nofollow noreferrer> std::endian
:
Since C++20 you can use std::endian
from the <type_traits>
header:
#include <type_traits>
int main()
{
static_assert(std::endian::native==std::endian::big,
"Not a big endian platform!");
}
这篇关于使用C ++ 11在编译时以编程方式查找字节序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!