我正在尝试使用struct作为键来增强序列化映射值,但是在编译代码时出现以下错误:
/usr/include/boost/serialization/access.hpp:116:11: error: ‘struct main(int, char**)::MyKey’ has no member named ‘serialize’
t.serialize(ar, file_version);
这是我正在使用的主要代码:
#include <ros/ros.h>
#include <map>
#include <fstream>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/serialization/map.hpp>
int main (int argc, char** argv)
{
ros::init (argc, argv, "training");
ros::NodeHandle nh;
struct MyKey {
int d0, d1, d2, a0, b0, a1, b1, a2, b2;
bool operator < (const MyKey& o) const {
return std::tie(d0, d1, d2, a0, b0, a1, b1, a2, b2) < std::tie(o.d0, o.d1, o.d2, o.a0, o.b0, o.a1, o.b1, o.a2, o.b2);
}
};
struct MyValue {
int p0, p1, p2;
};
std::map<MyKey, MyValue> pobj;
std::ofstream s("obj_pattern"); boost::archive::text_oarchive oa(s);
for(int i=0;i<5000000;i++) {
pobj.insert({{i, i+1, i+2, i+3, i+4, i+5, i+6, i+7, i+8}, {i+9, i+10, i+11}});
oa << pobj;
}
return 0;
}
如何清除此错误?
答案 0 :(得分:1)
如果要序列化用户定义的类型,则需要在类中添加 serialize 函数模板。通过这种方法,您可以说明要对类的哪些数据成员进行序列化/还原。
因为不能为 main 函数之外的 MyKey , MyValue 的本地类移动定义定义成员函数模板:
struct MyKey {
int d0, d1, d2, a0, b0, a1, b1, a2, b2;
bool operator < (const MyKey& o) const {
return std::tie(d0, d1, d2, a0, b0, a1, b1, a2, b2)
< std::tie(o.d0, o.d1, o.d2, o.a0, o.b0, o.a1, o.b1, o.a2, o.b2);
}
template<class Ar>
void serialize (Ar& ar, const unsigned int) {
ar & d0;
ar & d1;
// ditto
}
};
struct MyValue {
int p0, p1, p2;
template<class Ar>
void serialize(Ar& ar, const unsigned int) {
ar & p0;
ar & p1;
//
}
};
int main (int argc, char** argv)
{
//...
}
在构建地图后,您应该仅致电oa << pobj;
一次:
for(int i=0;i<5000000;i++) {
pobj.insert({{i, i+1, i+2, i+3, i+4, i+5, i+6, i+7, i+8}, {i+9, i+10, i+11}});
}
oa << pobj;