as_bytes功能的准确定义
Exact definition of as_bytes function
我在阅读时发现了这个函数,但我在 CPPreference 上找不到它的定义
Bjarne stroustrup的编程原理
它以这种方式使用:
ifs.read(as_bytes(x),sizeof(int));`
我了解read
的工作原理,但您仍然可以帮助我to_bytes
标准定义。
as_bytes
函数返回参数第一个字节的地址(因此read
调用将覆盖对象x
)。因此,在 C++11 或更高版本中,将按如下方式编写该函数:
template <class T>
char* as_bytes(T& x) {
return &reinterpret_cast<char&>(x);
// or:
// return reinterpret_cast<char*>(std::addressof(x));
}
评论中链接的版本早于 C++11。据推测,Stroustrup首先转换为void*
的原因是因为reinterpret_cast
不能保证在C++03中做正确的事情。另请注意,对于具有重载&
运算符的参数,旧版本将无法正常工作。
相关文章:
- 类模板的成员功能的定义在单独的TU中完全专业化
- C++ - 没有自定义交换功能的移动分配运算符?
- 如何定义可变参数类模板的成员模板功能
- '_HAS_CXX17'宏是否可用于自定义项目标头以启用C++17 语言集功能?
- C++模板功能并定义特定情况
- 这种错误的原因是什么:将"功能"重新定义为不同类型的符号
- 功能原型,没有定义
- 如何在cmake工具链文件中设置编译功能,以便已知的自定义编译器使用target_compile_features
- 如何在C 17中定义功能组成
- 如何自定义功能行为
- 在多态性中重新定义功能(虚拟),具有不同数量的参数
- 定义功能,以便它可以接受列表或向量
- 如何在自定义功能中使用C 构建器OpenArray
- 用户定义功能的返回值的分配:性能
- 使用自己的结构在标题类中定义功能
- 自定义功能不返回正确的值
- 全部使用用户自定义功能和MPI_BOTTOM
- 如何正确定义功能并实现它们
- 重新定义功能
- c++共享库定义和取消定义功能