1

I have class with the below structure,

class Myclass {
   int myInt;
   char myChar;
   UDFString str; //user-defined string class
   string myString;
   UDFObj obj; //this is user-defined class and It has char & byte pointers, also user-defined structs in it.
   Mystruct srt; //this has enums, char pointers and user-defined structs
   char *chrptr;
   map<int,strt> mp; // here strt is user defined struct which has byte pointer and ints.
} 

class encp {
   protected:
   stack<Myclass> *stk; 
}

I want to perform serialization of encp, so in boost serialize() if I specify stk, will it take care of all internal data structures that we have in Myclass for serialization automatically, if not how could we approach serializing encp with a boost? or if any other better approach for serialization above class data to binary please let me know.

1 Answers1

1

No, boost serialization will not automatically serialize anything. You need to provide a serialize() function for every (custom) type and implement it yourself. For example, a start could be:

#include <boost/serialization/map.hpp>
#include <boost/serialization/string.hpp>
#include <boost/serialization/stack.hpp>
#include <boost/archive/binary_oarchive.hpp>
#include <boost/archive/binary_iarchive.hpp>

class Myclass {
   int myInt;
   char myChar;
   UDFString str; //user-defined string class
   string myString;
   UDFObj obj; //this is user-defined class and It has char & byte pointers, also user-defined structs in it.
   Mystruct srt; //this has enums, char pointers and user-defined structs
   char *chrptr;
   map<int,strt> mp; // here strt is user defined struct which has byte pointer and ints.
   
   friend class boost::serialization::access;

   template<class Archive>
   void serialize(Archive & ar, const unsigned int version)
   {
     ar & myInt;
     ar & myChar;
     ar & str;
     ar & myString;
     ar & obj;
     ar & srt;
     ar & chrptr;
     ar & mp;
   }
} 

class encp {
protected:
   stack<Myclass> *stk; 
   
   friend class boost::serialization::access;

   template<class Archive>
   void serialize(Archive & ar, const unsigned int version)
   {
     ar & stk;
   }
}


int main()
{
  std::ofstream ofs("filename");
  boost::archive::binary_oarchive oa(ofs);
  oa << g;
}

You also need to provide proper serialize() functions for custom types such as UDFString, UDFObj, Mystruct and strt.

Please see the documentation and the tutorial for more information.

Note: Actually, you could also have a look at boost.pfr which does allow to bypass the manual implementation of serialize() for "simple" structs. See this answer.

Sedenion
  • 5,421
  • 2
  • 14
  • 42