有一些消息结构。每个都可以序列化为字符串并从字符串反序列化。
对于序列化部分,我使用重载运算符
struct S
{
int32_t type;
double a;
int32_t b;
bool c;
std::string d;
friend std::ostream& operator<< (std::ostream& os, const S& s)
{
os << "{field1" << "=" << s.a << "|";
os << "field2" << "=" << s.b << "|";
os << "field3" << "=" << s.c << "|";
os << "field4" << "=" << s.d << "}";
return os;
}
};
编辑:所以,我选择使用 xml 存档。但是,我还有另一个问题。由于消息有多种类型,可以通过字段 msgtype 进行分类。反序列化时,如何指定要反序列化到哪个对象?我需要手动搜索 msgtype 字段吗?
template <typename Archive>
void serialize(Archive &ar, const unsigned int version)
{
using boost::serialization::make_nvp;
ar & make_nvp("msgtype", type);
ar & make_nvp("field1", a);
ar & make_nvp("field2", b);
ar & make_nvp("field3", c);
ar & make_nvp("field4", d);
}
使用Boost序列化:
http://www.boost.org/doc/libs/1_52_0/libs/serialization/doc/index.html http://www.boost.org/doc/libs/1_52_0/libs/serialization/doc/index.html
有了这个库,它几乎可以为您处理所有事情。例如,您可以将此函数添加到您的结构中:
void serialize(Archive & ar, const unsigned int version)
{
ar & a;
ar & b;
ar & c;
ar & d;
}
然后您将能够通过执行以下操作来序列化和反序列化:
boost::archive::text_oarchive oa(ofs);
// write class instance to archive
oa << g;
和这个:
boost::archive::text_iarchive ia(ifs);
// read class state from archive
ia >> newg;
假设g
and newg
是你的结构。
然后您还可以更改为binary_archive
或其他以节省空间的方式,或text_archive
以保持可读性。
EDIT:对于您的编辑,Boost 序列化将为您处理反序列化。只要您序列化为存档,您只需对该存档执行与创建存档的类型相反的操作,boost 就会将所有内容放回到正确的位置。
我不熟悉 boost 中的 NVP 和 XML 内容,所以如果它有所不同,我很抱歉。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)