1 #ifndef MSP_DATAFILE_DYNAMICOBJECTLOADER_H_
2 #define MSP_DATAFILE_DYNAMICOBJECTLOADER_H_
4 #include <msp/core/typeregistry.h>
5 #include "collection.h"
15 Loads a dynamically typed object, with the type specified as a statement. The
16 T template parameter is the common base class for all possible loaded types.
18 template<typename T, typename C = Collection>
19 class DynamicObjectLoader: public Loader
28 void operator()(const std::string &, DynamicObjectLoader &) const;
31 typedef Msp::TypeRegistry<CreateObject, DynamicObjectLoader &> TypeRegistry;
37 std::function<void(Collection &, const std::string &, T *)> store_func;
39 static ActionMap shared_actions;
42 DynamicObjectLoader(Collection *);
44 ~DynamicObjectLoader() { delete object; delete obj_loader; }
47 virtual void init_actions();
50 T *get_object() { T *o = object; object = 0; return o; }
51 void store_object(Collection &, const std::string &);
54 void type(const Symbol &);
57 typename std::enable_if<NeedsCollection<typename U::Loader>::value, typename U::Loader *>::type create_object_loader(U &obj) const;
60 typename std::enable_if<!NeedsCollection<typename U::Loader>::value, typename U::Loader *>::type create_object_loader(U &obj) const;
63 virtual const TypeRegistry &get_type_registry() const = 0;
67 template<typename T, typename C>
68 Loader::ActionMap DynamicObjectLoader<T, C>::shared_actions;
70 template<typename T, typename C>
71 DynamicObjectLoader<T, C>::DynamicObjectLoader(Collection *c):
76 set_actions(shared_actions);
79 template<typename T, typename C>
80 void DynamicObjectLoader<T, C>::init_actions()
82 add("type", &DynamicObjectLoader::type);
85 template<typename T, typename C>
86 void DynamicObjectLoader<T, C>::store_object(Collection &c, const std::string &name)
89 throw std::logic_error("no store function");
91 store_func(c, name, object);
95 template<typename T, typename C>
96 void DynamicObjectLoader<T, C>::type(const Symbol &t)
99 throw std::logic_error("duplicate type statement");
101 get_type_registry().invoke(t.name, *this);
104 template<typename T, typename C>
106 typename std::enable_if<NeedsCollection<typename U::Loader>::value, typename U::Loader *>::type DynamicObjectLoader<T, C>::create_object_loader(U &obj) const
109 throw no_collection(typeid(U));
110 return new typename U::Loader(obj, *coll);
113 template<typename T, typename C>
115 typename std::enable_if<!NeedsCollection<typename U::Loader>::value, typename U::Loader *>::type DynamicObjectLoader<T, C>::create_object_loader(U &obj) const
117 return new typename U::Loader(obj);
121 template<typename T, typename C>
123 void DynamicObjectLoader<T, C>::CreateObject<U>::operator()(const std::string &, DynamicObjectLoader &ldr) const
127 ldr.obj_loader = ldr.create_object_loader<U>(*obj);
128 ldr.add_auxiliary_loader(*ldr.obj_loader);
129 ldr.store_func = [&ldr](Collection &c, const std::string &n, T *o){ c.add(n, static_cast<U *>(o)); };
132 } // namespace DataFile