In his recent talk “Type punning in modern C++” Timur Doumler said that std::bit_cast
cannot be used to bit cast a float
into an unsigned char[4]
because C-style arrays cannot be returned from a function. We should either use std::memcpy
or wait until C++23 (or later) when something like reinterpret_cast<unsigned char*>(&f)[i]
will become well defined.
In C++20, can we use an std::array
with std::bit_cast
,
float f = /* some value */;
auto bits = std::bit_cast<std::array<unsigned char, sizeof(float)>>(f);
instead of a C-style array to get bytes of a float
?
struct X { unsigned char elems[5]; };
satisfies the rule you're citing. It can certainly be list-initialized with up to 4 elements. It can also be list-initialized with 5 elements. I don't think any standard library implementer hates people enough to actually do this, but I think it's technically conformant. – Byerly