openMSX
serialize_stl.hh
Go to the documentation of this file.
1 #ifndef SERIALIZE_STL_HH
2 #define SERIALIZE_STL_HH
3 
4 #include "serialize_core.hh"
5 #include <vector>
6 #include <deque>
7 #include <list>
8 #include <map>
9 #include <set>
10 #include <iterator>
11 
12 namespace openmsx {
13 
14 template<typename T> struct serialize_as_stl_collection : std::true_type
15 {
16  static const int size = -1; // variable size
17  typedef typename T::value_type value_type;
18  // save
19  typedef typename T::const_iterator const_iterator;
20  static const_iterator begin(const T& t) { return t.begin(); }
21  static const_iterator end (const T& t) { return t.end(); }
22  // load
23  static const bool loadInPlace = false;
24  typedef typename std::insert_iterator<T> output_iterator;
25  static void prepare(T& t, int /*n*/) {
26  t.clear();
27  }
28  static output_iterator output(T& t) {
29  return std::inserter(t, t.begin());
30  }
31 };
32 
33 template<typename T> struct serialize_as_collection<std::list<T>>
34  : serialize_as_stl_collection<std::list<T>> {};
35 
36 template<typename T> struct serialize_as_collection<std::set<T>>
37  : serialize_as_stl_collection<std::set<T>> {};
38 
39 template<typename T> struct serialize_as_collection<std::deque<T>>
40  : serialize_as_stl_collection<std::deque<T>> {};
41 
42 template<typename T1, typename T2> struct serialize_as_collection<std::map<T1, T2>>
43  : serialize_as_stl_collection<std::map<T1, T2>> {};
44 
45 template<typename T> struct serialize_as_collection<std::vector<T>>
46  : serialize_as_stl_collection<std::vector<T>>
47 {
48  // Override load-part from base class.
49  // Don't load vectors in-place, even though it's technically possible
50  // and slightly more efficient. This is done to keep the correct vector
51  // size at all intermediate steps. This may be important in case an
52  // exception occurs during loading.
53  static const bool loadInPlace = false;
54  typedef typename std::back_insert_iterator<std::vector<T>>
56  static void prepare(std::vector<T>& v, int n) {
57  v.clear(); v.reserve(n);
58  }
59  static output_iterator output(std::vector<T>& v) {
60  return std::back_inserter(v);
61  }
62 };
63 
64 } // namespace openmsx
65 
66 #endif