如何知道变量是否可以直接写入二进制文件?

时间:2018-01-27 20:58:24

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

我写过这个函数:

[{
  "id" : "local-1517085058363",
  "name" : "TeraGen (5MB) 6e722700-0397-11e8-ae84-b54a3ebb27aa",
  "attempts" : [ {
    "startTime" : "2018-01-27T19:22:37.513GMT",
    "endTime" : "2018-01-27T19:22:43.253GMT",
    "lastUpdated" : "2018-01-27T19:22:43.000GMT",
    "duration" : 5740,
    "sparkUser" : "paulcarron",
    "completed" : true,
    "endTimeEpoch" : 1517080963253,
    "startTimeEpoch" : 1517080957513,
    "lastUpdatedEpoch" : 1517080963000
  } ]
} ] 

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

有三个选项:template <typename T> ofstream bfwrite(ofstream &os, const T &data) { os.write(reinterpret_cast<char*>(data), sizeof(data)); return os; } is_trivially_copyable或仅使用其他人的序列化库。学习语言时你可以做的一切都已经由其他人完成了,所以我坚持前两个选项中的一个。 is_pod对我来说足够安全。有关详细信息,请参阅接受的答案。

1 个答案:

答案 0 :(得分:4)

您需要的是http://en.cppreference.com/w/cpp/types/is_trivially_copyable特质。

  

普通可复制类型的对象是唯一可能的C ++对象   安全地使用std :: memcpy复制或序列化为/从二进制文件   使用std :: ofstream :: write()/ std :: ifstream :: read()。

具体来说,我强调:

  

一般来说,一个   平凡的可复制类型是底层字节可以使用的任何类型   将复制到char 或unsigned char数组并复制到新对象中   相同类型,结果对象将具有相同的值   作为原作。

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;
}