std::bit_cast with std::array

前端 未结 3 1897
孤独总比滥情好
孤独总比滥情好 2021-02-19 09:29

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]

3条回答
  •  春和景丽
    2021-02-19 09:51

    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 chars 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.

提交回复
热议问题