我解决了这个问题。
struct Base
{
Base() = default;
virtual ~Base() = default;
std::string common;
template <class Archive>
void serialize(Archive &ar)
{
ar(CEREAL_NVP(common));
}
};
struct A : public Base
{
A() = default;
A(int v)
{
a = v;
}
int a;
template <class Archive>
void serialize(Archive &ar)
{
ar(cereal::make_nvp("Base", cereal::base_class<Base>(this)));
ar(a);
}
};
struct B : public Base
{
B() = default;
B(std::string text)
{
b = text;
}
std::string b;
template <class Archive>
void serialize(Archive &ar)
{
ar(cereal::make_nvp("Base", cereal::base_class<Base>(this)));
ar(b);
}
};
struct Config
{
std::vector<std::shared_ptr<Base>> vector;
template <class Archive>
void serialize(Archive &ar)
{
ar(vector);
}
};
CEREAL_REGISTER_TYPE(A)
CEREAL_REGISTER_TYPE_WITH_NAME(B, "ClassB")
CEREAL_REGISTER_POLYMORPHIC_RELATION(Base, A)
CEREAL_REGISTER_POLYMORPHIC_RELATION(Base, B)
int main()
{
std::string workPath = "/home/user/"
{
std::ofstream os(workPath + "polymorphism_test.json");
cereal::JSONOutputArchive oarchive(os);
std::shared_ptr<Base> ptr1 = std::make_shared<A>(123);
std::shared_ptr<Base> ptr2 = std::make_shared<B>("foobar");
Config op;
op.vector.push_back(ptr1);
op.vector.push_back(ptr2);
oarchive(op);
}
{
std::ifstream is(workPath + "polymorphism_test.json");
cereal::JSONInputArchive iarchive(is);
Config ip;
iarchive(ip);
}
return 0;
}
输出:
{
"value0": {
"value0": [
{
"polymorphic_id": 2147483649,
"polymorphic_name": "A",
"ptr_wrapper": {
"id": 2147483649,
"data": {
"Base": {
"common": ""
},
"value0": 123
}
}
},
{
"polymorphic_id": 2147483650,
"polymorphic_name": "ClassB",
"ptr_wrapper": {
"id": 2147483650,
"data": {
"Base": {
"common": ""
},
"value0": "foobar"
}
}
}
]
}
}