我写了这个函数:
template <typename T>
ofstream bfwrite(ofstream &os, const T &data) {
os.write(reinterpret_cast<char*>(data), sizeof(data));
return os;
}
我知道这对某些类型不起作用,因为例如,它们指向堆上的数据。 所以我想做一个编译时检查,但我在引用中找不到合适的函数。
有3种选择:is_trivially_copyable
、is_pod
或者直接使用别人的序列化库。学习一门语言时,你能做的一切其他人都已经完成了,所以我会坚持前两个选项之一。
is_trivially_copyable
对我来说足够安全。有关详细信息,请参阅已接受的答案。
最佳答案
您需要的是 http://en.cppreference.com/w/cpp/types/is_trivially_copyable特质。
Objects of trivially-copyable types are the only C++ objects that may be safely copied with std::memcpy or serialized to/from binary files with std::ofstream::write()/std::ifstream::read().
具体来说,我强调的是:
In general, a trivially copyable type is any type for which the underlying bytes can be copied to an array of char or unsigned char and into a new object of the same type, and the resulting object would have the same value as the original.
template <typename T>
ofstream bfwrite(ofstream &os, const T &data)
{
static_assert(std::is_trivially_copyable<T>::value, "T must be trivially copyable");
os.write(reinterpret_cast<char*>(data), sizeof(data));
return os;
}
或者,如果您需要 sfine ,像这样:
template <typename T>
typename std::enable_if<std::is_trivially_copyable<T>::value,
ofstream>::type bfwrite(ofstream &os, const T &data)
{
os.write(reinterpret_cast<char*>(data), sizeof(data));
return os;
}
关于c++ - 我怎么知道变量是否可以直接写入二进制文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48480500/