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]
Per [array]/1-3:
The header
defines a class template for storing fixed-size sequences of objects. An array is a contiguous container. An instance of
array
storesN
elements of typeT
, so thatsize() == N
is an invariant.An array is an aggregate that can be list-initialized with up to
N
elements whose types are convertible toT
.An array meets all of the requirements of a container and of a reversible container (
[container.requirements]
), except that a default constructed array object is not empty and that swap does not have constant complexity. An array meets some of the requirements of a sequence container. Descriptions are provided here only for operations on array that are not described in one of these tables and for operations where there is additional semantic information.
The standard does not actually require std::array
to have exactly one public data member of type T[N]
, so in theory it is possible that sizeof(To) != sizeof(From)
or is_trivially_copyable_v
.
I will be surprised if this doesn't work in practice, though.