]> git.tdb.fi Git - libs/datafile.git/blob - source/objectloader.h
76fc412abed60db13c7b7e4b80837ffad0ca93df
[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: virtual 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         template<typename T>
54         DerivedObjectLoader(O &o, T &a): B(o, a), obj(o) { }
55
56 public:
57         O &get_object() const { return obj; }
58 };
59
60
61 /**
62 Provides functionality for loading objects with a Collection.  Deriving from
63 this allows loading pointers to objects in the collection automatically.
64 */
65 template<typename O, typename C = Collection>
66 class CollectionObjectLoader: public ObjectLoader<O>
67 {
68 public:
69         typedef C Collection;
70
71 protected:
72         C *coll;
73
74         CollectionObjectLoader(O &o, C *c): ObjectLoader<O>(o), coll(c) { }
75
76 public:
77         C &get_collection() const
78         {
79                 if(!coll)
80                         throw no_collection(typeid(O));
81                 return *coll;
82         }
83 };
84
85 } // namespace DataFile
86 } // namespace Msp
87
88 #endif