如何向std::bit_cast传入数组指针类型参数?
能否将数组首元素的地址作为参数传递给std::bit_cast?
不能直接将数组首元素的地址(指针类型)传递给std::bit_cast,下面结合代码和编译错误详细说明:
示例代码
#include <bit> #include <iostream> struct A { int a; int b; int c; int d; int e; void print() { std::cout << a << ", " << b << ", " << c << ", " << d << ", " << e << std::endl; } }; int main() { char arr[20]{}; // arr is filled with some data A a = std::bit_cast<A>(arr); a.print(); const char* arrp = arr; // doesn't compile A b = std::bit_cast<A>(arrp); b.print(); }
编译错误信息
<source>: 在函数'int main()'中: <source>:23:27: 错误:找不到匹配的函数调用‘bit_cast<A>(const char*&)’ 23 | A b = std::bit_cast<A>(arrp); | ~~~~~~~~~~~~~~~~^~~~~~ 从<source>:1包含的文件中: /opt/compiler-explorer/gcc-13.2.0/include/c++/13.2.0/bit:81:5: 注意:候选函数:'template<class _To, class _From> constexpr _To std::bit_cast(const _From&) requires sizeof (_To) == sizeof (_From) && __is_trivially_copyable(_To) && __is_trivially_copyable(_From)' 81 | bit_cast(const _From& __from) noexcept | ^~~~~~~~ /opt/compiler-explorer/gcc-13.2.0/include/c++/13.2.0/bit:81:5: 注意:模板参数推导/替换失败: /opt/compiler-explorer/gcc-13.2.0/include/c++/13.2.0/bit:81:5: 注意:约束条件不满足 /opt/compiler-explorer/gcc-13.2.0/include/c++/13.2.0/bit: 在替换'template<class _To, class _From> constexpr _To std::bit_cast(const _From&) requires sizeof (_To) == sizeof (_From) && __is_trivially_copyable(_To) && __is_trivially_copyable(_From) [with _To = A; _From = const char*]'时: <source>:23:27: 从这里要求实例化 /opt/compiler-explorer/gcc-13.2.0/include/c++/13.2.0/bit:81:5: 被'template<class _To, class _From> constexpr _To std::bit_cast(const _From&) requires sizeof (_To) == sizeof (_From) && __is_trivially_copyable(_To) && __is_trivially_copyable(_From)'的约束条件要求 /opt/compiler-explorer/gcc-13.2.0/include/c++/13.2.0/bit:83:27: 注意:表达式'sizeof (_To) == sizeof (_From) [with _To = A; _From = const char*]'的值为'false' 83 | requires (sizeof(_To) == sizeof(_From)) | ~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~ 编译器返回:1
错误原因
std::bit_cast有三个核心约束条件:
- 源类型
_From和目标类型_To的内存大小必须完全相等 - 源类型和目标类型都必须是**可平凡复制(trivially copyable)**的类型
- 目标类型必须是可平凡构造(trivially constructible)的类型
你的代码中,struct A的大小是20字节(5个int成员,每个占4字节),而const char*是指针类型,在64位系统上占8字节、32位系统上占4字节,显然和A的大小不匹配,直接触发第一个约束条件检查失败,导致编译器报错。
替代方案
如果想要从指针指向的内存区域转换为A类型,推荐使用std::memcpy,这是符合标准且更安全的做法:
const char* arrp = arr; A b{}; std::memcpy(&b, arrp, sizeof(A)); b.print();
如果坚持使用std::bit_cast,可以将指针指向的内存转换为对应大小的数组类型引用(需确保指针指向的内存足够且对齐正确):
const char* arrp = arr; A b = std::bit_cast<A>(*reinterpret_cast<const std::array<char, sizeof(A)>*>(arrp)); b.print();
内容的提问来源于stack exchange,提问作者Harry
相关产品推荐
相关产品推荐

