【发布时间】:2020-02-07 17:53:39
【问题描述】:
在他最近的谈话“Type punning in modern C++” Timur Doumler said 中,std::bit_cast 不能用于将float 位转换为unsigned char[4],因为不能从函数返回 C 样式的数组。我们应该要么使用std::memcpy,要么等到C++23(或更高版本),当reinterpret_cast<unsigned char*>(&f)[i]之类的东西会变得很好定义时。
在 C++20 中,我们可以使用 std::array 和 std::bit_cast,
float f = /* some value */;
auto bits = std::bit_cast<std::array<unsigned char, sizeof(float)>>(f);
而不是 C 样式的数组来获取 float 的字节?
【问题讨论】:
标签: c++ c++20 type-punning