如何使用Boost序列化std :: chrono :: duration?

时间:2017-02-12 10:07:48

标签: serialization boost duration boost-serialization chrono

是否可以使用std::chrono::duration序列化std::chrono::milliseconds或特别boost::serialization

发生以下错误:

  

" struct std :: chrono :: duration>'没有名为'serialize"

的成员

我的模板类需要这个:

#include <iostream>
#include <chrono>
#include <boost/serialization/serialization.hpp>

template<typename T>
class Field {
public:

// Default Constructor
Field() {}

Field(std::string name, T value) :
        mName(name), mValue(value) {}

~Field() {}

const std::string& getName() const {
    return mName;
}

T getValue() const {
    return mValue;
}

private:

friend class boost::serialization::access;
template<typename Archive>
void serialize(Archive& archive, const unsigned int) {
    archive & boost::serialization::make_nvp("Name", mName);
    archive & boost::serialization::make_nvp("Value", mValue);
}

std::string mName;
T mValue;
};

BOOST_CLASS_IMPLEMENTATION( Field<int>, boost::serialization::object_serializable )
BOOST_CLASS_IMPLEMENTATION( Field<std::chrono::milliseconds>, boost::serialization::object_serializable )

我正在创建以下对象:

Field<std::chrono::milliseconds> mSimTime;

1 个答案:

答案 0 :(得分:1)

我们说你有:

auto earlier = std::chrono::system_clock::now();
auto now = std::chrono::system_clock::now();
auto aLotOfMilliseconds= std::chrono::duration_cast<std::chrono::milliseconds>(
        now - earlier);

//在这里序列化int64_t。

然后在反序列化之后,你有:

std::chrono::duration<int64_t, std::milli> duration(aLotOfMilliseconds);