Person.h

#ifndef PersonH
#define PersonH

#include <string> // for std::string

#include <boost/serialization/access.hpp>

class Person
{
public:
  Person();

public:
  int age;
  bool sex;
  std::string name;

private:
  friend class boost::serialization::access;
  template<class Archive>
  void serialize(Archive& ar, const unsigned int version)
  {
    ar & age;
    ar & sex;
    ar & name;
  }
};

#endif // PersonH



Person.cpp

#include "Person.h"

Person::Person()
{
  age = 39;
  sex = true;
  name = "gilgil";
}



person_test.cpp


#include "Person.h"

#include <fstream>

#include <boost/archive/text_oarchive.hpp>
void saveTest()
{
  const Person person;

  std::ofstream ofs("person.dat");
  boost::archive::text_oarchive oa(ofs);
  oa << person;
}

#include <boost/archive/text_iarchive.hpp>
void loadTest()
{
  Person person;

  std::ifstream ifs("person.dat");
  boost::archive::text_iarchive ia(ifs);
  ia >> person;
}

int main()
{
  saveTest();
  loadTest();
}



1. To make class serialized, you need to write"serialize" function in class header file(Person.h).

2. The only file you have to include in class header file is "boost/serialization/access.hpp".

3. Serialize template function(void serialize) is actually code-implemented where related archive codes(person_test.cpp) exist.