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]
Yes, this works on all major compilers, and as far as I can tell from looking at the standard, it is portable and guaranteed to work.
First of all, std::array
is guaranteed to be an aggregate (https://eel.is/c++draft/array#overview-2). From this follows that it holds exactly a sizeof(float)
number of char
s inside (typically as a char[]
, although afaics the standard doesn't mandate this particular implementation - but it does say the elements must be contiguous) and cannot have any additional non-static members.
It is therefore trivially copyable, and its size matches that of float
as well.
Those two properties allow you to bit_cast
between them.