c++ - 我怎么知道变量是否可以直接写入二进制文件?

标签 c++ visual-studio file c++14

我写了这个函数:

template <typename T>
ofstream bfwrite(ofstream &os, const T &data) {
    os.write(reinterpret_cast<char*>(data), sizeof(data));
    return os;
}

我知道这对某些类型不起作用,因为例如,它们指向堆上的数据。 所以我想做一个编译时检查,但我在引用中找不到合适的函数。

有3种选择:is_trivially_copyableis_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/

相关文章:

c++ - 如何从文件中删除记录?

c++ - `operator>>' 不是 `Instance' 的成员

visual-studio - Xamarin 是否支持用于 NuGet 的 project.json?

visual-studio - 在Visual Studio 2010的预生成步骤中吞下错误

C++由于多次包含头文件而重新定义

file - 使用带文件名的存储桶在 s3 存储桶中搜索文件

ios - 在 MAC 和 iOS 中收听文件更新

c++ - 如果我在 for 中声明一个对象,它的内存会在 for 之后被释放吗?

c++ - 打包一个 HTML5 应用并将其部署在桌面上

c# - Resharper 4.5 中的解决方案范围分析中断?