]> git.tdb.fi Git - libs/datafile.git/blob - source/objectloader.h
4dcb981864e7c2d924a61dcbd44e552dfffa6cb0
[libs/datafile.git] / source / objectloader.h
1 #ifndef MSP_DATAFILE_OBJECTLOADER_H_
2 #define MSP_DATAFILE_OBJECTLOADER_H_
3
4 #include <typeinfo>
5 #include "loader.h"
6
7 namespace Msp {
8 namespace DataFile {
9
10 class no_collection: public std::runtime_error
11 {
12 public:
13         no_collection(const std::type_info &);
14 };
15
16 class Collection;
17
18 /**
19 Provides the basic functionality of an object loader.  Deriving from this
20 allows loading values directly into member variables of the objects.
21 */
22 template<typename O>
23 class ObjectLoader: public Loader
24 {
25 public:
26         typedef O Object;
27
28 protected:
29         O &obj;
30
31         ObjectLoader(O &o): obj(o) { }
32
33 public:
34         O &get_object() const { return obj; }
35 };
36
37
38 /**
39 Convenience class for loading derived objects.  Inherits from the base class
40 loader and shadows its members with ones for the derived type.
41 */
42 template<typename O, typename B>
43 class DerivedObjectLoader: public B
44 {
45 public:
46         typedef O Object;
47
48 protected:
49         O &obj;
50
51         DerivedObjectLoader(O &o): B(o), obj(o) { }
52
53 public:
54         O &get_object() const { return obj; }
55 };
56
57
58 /**
59 Provides functionality for loading objects with a Collection.  Deriving from
60 this allows loading pointers to objects in the collection automatically.
61 */
62 template<typename O, typename C = Collection>
63 class CollectionObjectLoader: public ObjectLoader<O>
64 {
65 public:
66         typedef C Collection;
67
68 protected:
69         C *coll;
70
71         CollectionObjectLoader(O &o, C *c): ObjectLoader<O>(o), coll(c) { }
72
73 public:
74         C &get_collection() const
75         {
76                 if(!coll)
77                         throw no_collection(typeid(O));
78                 return *coll;
79         }
80 };
81
82 } // namespace DataFile
83 } // namespace Msp
84
85 #endif