Ticket #2984: boost_serialize_protected_bug.cc

File boost_serialize_protected_bug.cc, 2.1 KB (added by Eric Moyer <eric_moyer@…>, 13 years ago)
Line 
1#include <iostream>
2#include <fstream>
3#include <boost/archive/text_oarchive.hpp>
4#include <boost/archive/text_iarchive.hpp>
5#include <boost/serialization/export.hpp>
6#include <boost/serialization/base_object.hpp>
7
8using namespace boost;
9using namespace std;
10
11//#define THRUBASE //To perform the serialization through a base class pointer
12#undef THRUBASE //To perform the serialization through a derived class instance
13#define INCL_SERIALIZE
14//#define BASE2ACCESS public
15#define BASE2ACCESS protected
16//#define BASE2ACCESS private
17
18class Base1{
19 friend class boost::serialization::access;
20public:
21 Base1():foo1(1){};
22 virtual void print(){ cout << "Base:" << foo1 << endl;}
23protected:
24 int foo1;
25private:
26#ifdef INCL_SERIALIZE
27 template<class Archive>
28 void serialize(Archive & ar, const unsigned int version){
29 ar & foo1;
30 }
31#endif
32};
33
34#ifdef INCL_SERIALIZE
35BOOST_CLASS_EXPORT_GUID(Base1,"bugtry.Base1")
36#endif
37
38
39class Base2{
40 friend class boost::serialization::access;
41public:
42 Base2():foo2(2){};
43 virtual void print(){ cout << "Base:" << foo2 << endl;}
44protected:
45 int foo2;
46private:
47#ifdef INCL_SERIALIZE
48 template<class Archive>
49 void serialize(Archive & ar, const unsigned int version){
50 ar & foo2;
51 }
52#endif
53};
54
55#ifdef INCL_SERIALIZE
56BOOST_CLASS_EXPORT_GUID(Base2,"bugtry.Base2")
57#endif
58
59class Derived:public Base1, BASE2ACCESS Base2{
60 friend class boost::serialization::access;
61public:
62 Derived():bar(3){};
63 virtual void print(){
64 cout << "Derived:" << foo1 << "," << foo2 << "," << bar << endl;}
65private:
66 int bar;
67#ifdef INCL_SERIALIZE
68 template<class Archive>
69 void serialize(Archive & ar, const unsigned int version){
70 ar & boost::serialization::base_object<Base1>(*this);
71 ar & boost::serialization::base_object<Base2>(*this);
72 ar & bar;
73 }
74#endif
75};
76
77#ifdef INCL_SERIALIZE
78BOOST_CLASS_EXPORT_GUID(Derived,"bugtry.Derived")
79#endif
80
81int main(int argc,char **argv) {
82 Derived d;
83 Base1* b = &d;
84 b->print();
85#ifdef INCL_SERIALIZE
86 ofstream o("bugtry.out");
87 boost::archive::text_oarchive out(o);
88#ifdef THRUBASE
89 out << b;
90#else
91 // out << d;
92#endif
93#endif
94
95 return 0;
96}