问题描述
在他最近的演讲中现代C ++中的类型修剪" Timur Doumler 说说,不能使用std::bit_cast
将float
强制转换为unsigned char[4]
因为无法从函数返回C样式的数组.我们应该使用std::memcpy
或等到C ++ 23(或更高版本)定义类似reinterpret_cast<unsigned char*>(&f)[i]
之类的东西时.
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.
在C ++ 20中,我们能否将std::array
与std::bit_cast
一起使用
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);
而不是C样式的数组来获取float
的字节?
instead of a C-style array to get bytes of a float
?
推荐答案
是的,这适用于所有主要的编译器,据我观察标准可以确定,它是可移植的并且可以保证正常工作.
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.
首先,保证std::array<unsigned char, sizeof(float)>
是一个集合( https://eel.is/c++draft/array#overview-2 ).由此可见,它内部恰好包含sizeof(float)
个char
数(通常为char[]
,尽管从原则上讲,该标准并未强制要求该特定实现-但它确实说元素必须是连续的),并且不能具有任何其他非静态成员.
First of all, std::array<unsigned char, sizeof(float)>
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.
因此可以轻松复制,并且其大小也与float
的大小匹配.
It is therefore trivially copyable, and its size matches that of float
as well.
这两个属性允许您在两个属性之间bit_cast
.
Those two properties allow you to bit_cast
between them.
这篇关于std :: bit_cast与std :: array的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!