I am looking for a nice way to serialize a certain class in C++. The main feature of this class is a list/vector/collection of std::shared_ptr<base_class>
, where there can be different subclasses of base_class
.
So far, I have tried implementing this using the cereal library with initial success. The generated JSON file looks like
{
"value0": [
{
"polymorphic_id": 2147483649,
"polymorphic_name": "DerivedClassOne",
"ptr_wrapper": {
"id": 2147483649,
"data": {
"value0": 0
}
}
},
{
"polymorphic_id": 2147483650,
"polymorphic_name": "DerivedClassTwo",
"ptr_wrapper": {
"id": 2147483650,
"data": {
"value0": 0.0
}
}
}
]
}
I guess this is fine for use cases where humans are not involved. However, the reason why I look at this feature is that users can write their own (configuration) files such as the following example:
{
"value0": [
{
"DerivedClassOne": {
"MemberOfDerivedClassOne": 1
}
},
{
"DerivedClassTwo": {
"MemberOfDerivedClassTwo": 1
}
}
]
}
where DerivedClassOne
and DerivedClassTwo
are subclasses of the common base_class
.
Is this possible? I am not asking for complete solutions, of course. But comments on the possibility and reasonability of such an approach would be very helpful.
EDIT 1: I heard good things about cereal, hence I am using it for those tests. I would be happy with any other modern C++ header only library. Implementing own serialization functions from scratch can be seen as last resort.
EDIT 2: For cereal, the question boils down to: Is there a nice way to serialize polymorph objects without the polymorphic_id
, ptr_wrapper
, or id
fields (which are not very user friendly IMHO)?