1 | #include <fstream>
|
---|
2 | #include <iostream>
|
---|
3 | #include <vector>
|
---|
4 |
|
---|
5 | #include <boost/archive/text_oarchive.hpp>
|
---|
6 | #include <boost/archive/text_iarchive.hpp>
|
---|
7 | #include <boost/serialization/vector.hpp>
|
---|
8 | #include <boost/foreach.hpp>
|
---|
9 |
|
---|
10 |
|
---|
11 |
|
---|
12 | class A {
|
---|
13 | public:
|
---|
14 | A() : a(2) {}
|
---|
15 | int a;
|
---|
16 | template<class Archive> void serialize(Archive& ar, const unsigned int version)
|
---|
17 | {
|
---|
18 | ar & a;
|
---|
19 | }
|
---|
20 |
|
---|
21 | };
|
---|
22 |
|
---|
23 |
|
---|
24 | class B {
|
---|
25 | public:
|
---|
26 | std::vector<A> v;
|
---|
27 | template<class Archive> void serialize(Archive& ar, const unsigned int version)
|
---|
28 | {
|
---|
29 | ar & v;
|
---|
30 | }
|
---|
31 | };
|
---|
32 |
|
---|
33 |
|
---|
34 |
|
---|
35 | int main() {
|
---|
36 |
|
---|
37 | // Create a B that contains a vector of 3 A's.
|
---|
38 | B b1;
|
---|
39 | b1.v.resize(3);
|
---|
40 | b1.v[0].a = 5;
|
---|
41 | b1.v[1].a = 6;
|
---|
42 | b1.v[2].a = 7;
|
---|
43 |
|
---|
44 | // Write it out.
|
---|
45 | {
|
---|
46 | std::ofstream ofs("data");
|
---|
47 | boost::archive::text_oarchive oa(ofs);
|
---|
48 | oa << b1;
|
---|
49 | }
|
---|
50 |
|
---|
51 | // Load it back into a B that already contains 2 elements.
|
---|
52 | B b2;
|
---|
53 | b2.v.resize(2);
|
---|
54 | b2.v[0].a = 20;
|
---|
55 | b2.v[1].a = 21;
|
---|
56 | {
|
---|
57 | std::ifstream ifs("data");
|
---|
58 | boost::archive::text_iarchive ia(ifs);
|
---|
59 | ia >> b2;
|
---|
60 | }
|
---|
61 | BOOST_FOREACH(const A& a, b2.v) {
|
---|
62 | std::cout << a.a << std::endl;
|
---|
63 | }
|
---|
64 |
|
---|
65 |
|
---|
66 | }
|
---|
67 |
|
---|