0

My situation is as follow, as part of testing an API interface I need to save some references (structure and vectors of structures) as XML. The saved XML file would eventually be used to retrieve the reference structure and compare to the current state. I am looking for a library that could help me solving that problem and found that the cereal library seems a good option.

I just find myself writting a lot of boilerplate code and wonder if I am using the library the way it is intended to.

Example: I want to serialise the structure A from the API since I can't modify A directly to add the serialise method, I need to create a structure B that inherits from A in order to serialise all the attributes of A.

struct A {
    int foo;
    float bar;
    std::string some_text;
};

struct B: public A {
    template <class Archive>
    void serialize( Archive & ar)
    {
        ar(cereal::make_nvp("foo", foo));
        ar(cereal::make_nvp("bar", bar));
        ar(cereal::make_nvp("some_text", some_text));
    }
};

1) Is that the right way of using cereal?

2) Is there a better way or another library that would allow me to have the same result with less boilerplate code? (Remember that there is quite a few structures that needs to be serialised)

Note: structures can be nested with other structures from the same API.

Guillaume.P
  • 421
  • 1
  • 4
  • 12

1 Answers1

0

The best solution I have found to reduce the boilerplate code as much as possible is to proceed as follow (for the same example):

struct A {
    int foo;
    float bar;
    std::string some_text;
};

namespace cereal
{
    template<class Archive>
    void serialize( Archive & ar, A & data )
    {
        ar(cereal::make_nvp("foo", data.foo)); // or even ar(CEREAL_NVP(data .foo)) if you don't mind the name being 'data.foo'
        ar(cereal::make_nvp("bar", data .bar));
        ar(cereal::make_nvp("some_text", data .some_text));
    }
}

Even though the documentation does not seem to implement it that way Specializing the archive

If someone has a better way of doing that I am still looking for a better solution.

Guillaume.P
  • 421
  • 1
  • 4
  • 12