Back to TILs

cereal - A C++11 library for serialization - 05

C++ serialization cereal

#include <iostream>
#include <vector>
#include <string>

using namespace std;

#include <cereal/archives/json.hpp>
#include <cereal/types/vector.hpp> // See details in http://uscilab.github.io/cereal/stl_support.html

class MyClass {
  int x, y, z;

  class MyOtherClass {
    string name, description;

  public:
    template <class Archive>
    void serialize( Archive &archive )
    {
      archive( CEREAL_NVP( name ), CEREAL_NVP( description ) );
    }
  };

  vector<MyOtherClass> Vector;
  vector<int>          ints;

public:
  template <class Archive>
  void serialize( Archive &archive )
  {
    archive( CEREAL_NVP( x ), CEREAL_NVP( y ), CEREAL_NVP( z ), CEREAL_NVP( ints ) );
  }

  // Add one element to the private vector
  void populateVector( const int value ) {
    ints.push_back( value );
  }
};

int main()
{
  MyClass  MyObject{};

  MyObject.populateVector( 101 );
  MyObject.populateVector( 202 );
  MyObject.populateVector( 303 );

  // For brevity I just print it to the standard output instead of the binary file
  cereal::JSONOutputArchive oarchive( cout );
  oarchive( MyObject );

  return 0;
}