Debian Codegraph @

examples/SerializableTemplate2.hh

raw
1 //
2 // Example simple template without a default constructor.
3 //
4 // The type upon which this template is parameterized
5 // must itself have the copy constructor but not necessarily
6 // the default constructor.
7 //
8 // In comparison with "SerializableTemplate1", the "restore"
9 // method has been replaced with the "read" method.
10 //
11
12 #ifndef GSEXAMPLES_SERIALIZABLETEMPLATE2_HH_
13 #define GSEXAMPLES_SERIALIZABLETEMPLATE2_HH_
14
15 #include <cassert>
16 #include "geners/ClassId.hh"
17 #include "geners/CPP11_auto_ptr.hh"
18
19 // In order to read/write arbitrary types, you will need to include
20 // the following header file
21 #include "geners/GenericIO.hh"
22
23 template<typename T>
24 class SerializableTemplate2
25 {
26 public:
27 inline SerializableTemplate2(const T& value) : datum_(value) {}
28
29 inline const T& datum() const {return datum_;}
30
31 // Operators which compare objects for equality are very useful
32 // for I/O testing
33 inline bool operator==(const SerializableTemplate2& r) const
34 {return datum_ == r.datum_;}
35 inline bool operator!=(const SerializableTemplate2& r) const
36 {return !(*this == r);}
37
38 // I/O methods needed for writing
39 inline gs::ClassId classId() const {return gs::ClassId(*this);}
40 inline bool write(std::ostream& of) const
41 {
42 // The following function should be used to write out single
43 // objects in a generic manner
44 return gs::write_item(of, datum_);
45 }
46
47 // I/O methods needed for reading
48 static inline const char* classname()
49 {
50 static const std::string myClassName(
51 gs::template_class_name<T>("SerializableTemplate2"));
52 return myClassName.c_str();
53 }
54 static inline unsigned version() {return 1;}
55 static inline SerializableTemplate2* read(const gs::ClassId& /* id */,
56 std::istream& in)
57 {
58 // How do we read back in a generic way an object which might
59 // not have a default constructor? We can't construct it on the
60 // stack here -- in this scope we do not have enough information
61 // to figure out how to build it. Instead, we need to call the
62 // "gs::read_item" function which reads back single objects and
63 // places them on the heap (gs::read_item will invoke the "read"
64 // method of the class if the class has one -- or will work in
65 // other ways appropriate for type T). gs::read_item either
66 // succeeds or throws an exception.
67 //
68 CPP11_auto_ptr<T> ptr = gs::read_item<T>(in);
69
70 // Now, we can make an object of this class by copying
71 // the T object we've just read back
72 //
73 return new SerializableTemplate2<T>(*ptr);
74 }
75
76 private:
77 T datum_;
78 };
79
80 #endif // GSEXAMPLES_SERIALIZABLETEMPLATE2_HH_