jeudi 29 septembre 2016

Finding endian-ness programatically at compile-time using C++11

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.

With some modifications, I am able to compile a similar solution with g++ & clang++ (-std=c++11) without any warning.

union U1
{
  uint8_t c[4];
  uint32_t i;
};
union U2
{
  uint32_t i;
  uint8_t c[4];
};

constexpr U1 u1 = {1, 0, 0, 0};
constexpr U2 u2 = {0x1};

constexpr bool is_little_endian ()
{
  return u1.c[0] == uint8_t(u2.i);
}

static_assert(is_little_endian(), "The machine is BIG endian");

Demo.

Can this be considered a deterministic method to decide the endian-ness or does it miss type-punning or something else?

Aucun commentaire:

Enregistrer un commentaire