我试图在boost :: chrono :: time_point tp类型的struct中序列化成员,但是给出错误序列化不是boost :: chrono :: time_point的成员,下面是我的代码:
struct myTimestamp
{
boost::chrono::time_point<boost::chrono::high_resolution_clock> begin1;
boost::chrono::time_point<boost::chrono::high_resolution_clock> end1;
private:
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive &ar, const unsigned int version)
{
ar & begin1;
ar & end1;
}
public:
myTimestamp();
virtual ~myTimestamp();
};
我已经包含了所有必需的头文件仍然问题仍然存在。
我甚至在序列化方法中尝试过以下选项..仍然相同
ar&amp; boost :: serialization :: make_binary_object(&amp; begin1,sizeof(begin1)); ar&amp; boost :: serialization :: make_binary_object(&amp; end1,sizeof(end1));
答案 0 :(得分:0)
好的,这是评论所暗示的内容:
using hr_clock = boost::chrono::high_resolution_clock;
using time_point = boost::chrono::time_point<hr_clock>;
namespace boost { namespace archive {
template<class Archive, typename clock>
void load(Archive& ar, boost::chrono::time_point<clock>& tp, unsigned)
{
using namespace boost::chrono;
milliseconds::rep millis;
ar & millis;
tp = time_point<clock>(milliseconds(millis));
}
template<class Archive, typename clock>
void save(Archive& ar, boost::chrono::time_point<clock> const& tp, unsigned)
{
using namespace boost::chrono;
milliseconds::rep millis = duration_cast<milliseconds>(tp.time_since_epoch()).count();
ar & millis;
}
} }
注意
since_epoch
在这方面令人困惑)供参考
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/serialization/serialization.hpp>
#include <boost/serialization/split_free.hpp>
#include <boost/chrono.hpp>
using hr_clock = boost::chrono::high_resolution_clock;
using time_point = boost::chrono::time_point<hr_clock>;
namespace boost { namespace archive {
template<class Archive, typename clock>
void load(Archive& ar, boost::chrono::time_point<clock>& tp, unsigned)
{
using namespace boost::chrono;
milliseconds::rep millis;
ar & millis;
tp = time_point<clock>(milliseconds(millis));
}
template<class Archive, typename clock>
void save(Archive& ar, boost::chrono::time_point<clock> const& tp, unsigned)
{
using namespace boost::chrono;
milliseconds::rep millis = duration_cast<milliseconds>(tp.time_since_epoch()).count();
ar & millis;
}
template<class Archive, typename clock>
inline void serialize(Archive & ar, boost::chrono::time_point<clock>& tp, unsigned version)
{
boost::serialization::split_free(ar, tp, version);
}
} }
struct myTimestamp
{
time_point begin1;
time_point end1;
private:
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive &ar, unsigned)
{
ar & begin1;
ar & end1;
}
public:
myTimestamp()
: begin1(hr_clock::now()),
end1(hr_clock::now() + boost::chrono::hours(1))
{ }
virtual ~myTimestamp() { }
};
#include <sstream>
int main()
{
std::stringstream ss;
{
myTimestamp ts;
boost::archive::text_oarchive oa(ss);
oa << ts;
}
{
myTimestamp ts;
boost::archive::text_iarchive ia(ss);
ia >> ts;
boost::archive::text_oarchive oa(std::cout);
oa << ts;
}
}