as_bytes功能的准确定义

Exact definition of as_bytes function

本文关键字:定义 功能 bytes as      更新时间:2023-10-16

我在阅读时发现了这个函数,但我在 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中做正确的事情。另请注意,对于具有重载&运算符的参数,旧版本将无法正常工作。