1

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)?

carlosvalderrama
  • 465
  • 1
  • 6
  • 22
  • 1
    I have a similar application and would be grateful for any pointers! – lucky_luke Feb 25 '20 at 21:34
  • Add serialization functions to the base class and make them virtual. Let the children implement them. – Thomas Matthews Feb 25 '20 at 21:41
  • @ThomasMatthews Are you suggesting implementing own serialization functions from scratch? While I would be willing to do this as last resort, I'd prefer to base on an existing library. – carlosvalderrama Feb 25 '20 at 21:56
  • I have not used the cereal library. Polymorphism looks like it would solve your issue. Verify how you can use cereal library and inheritance. – Thomas Matthews Feb 25 '20 at 22:01

0 Answers0