Classdesc 3.44
factory.h
1/*
2 @copyright Russell Standish 2000-2013
3 @author Russell Standish
4 This file is part of Classdesc
5
6 Open source licensed under the MIT license. See LICENSE for details.
7*/
8
9#ifndef CLASSDESC_FACTORY_H
10#define CLASSDESC_FACTORY_H
11#include "classdesc.h"
12#include <sstream>
13
14namespace classdesc
15{
18 template <class B, class Type>
19 class Factory
20 {
21 struct CreatorBase
22 {
23 virtual ~CreatorBase() {}
24 virtual B* create() const=0;
25 };
26 typedef std::map<Type, shared_ptr<CreatorBase> > Fmap;
27 Fmap fmap;
28
29 template <class T>
30 struct Creator: public CreatorBase
31 {
32 B* create() const {return new T();}
33 };
34 public:
35
37 template <class T>
38 void registerType(const Type& t)
39 {
40 fmap.insert
41 (make_pair(t, shared_ptr<CreatorBase>(new Creator<T>)));
42 }
43
44 template <class T> void registerType()
45 {registerType<T>(T().type());}
46
47
59
61
62 struct InvalidType: public exception
63 {
64 string s;
65 InvalidType(const Type& t) {
66 std::ostringstream os;
67 os<<"invalid type "<<t;
68 s=os.str();
69 }
70 const char* what() const throw() {return s.c_str();}
71 ~InvalidType() throw() {}
72 };
73
75 B* create(const Type& t) const
76 {
77 typename Fmap::const_iterator i=fmap.find(t);
78 if (i==fmap.end())
79 throw InvalidType(t);
80 else
81 return i->second->create();
82 }
83
85 std::vector<string> types() const
86 {
87 std::vector<string> r;
88 for (typename Fmap::const_iterator i=fmap.begin(); i!=fmap.end(); ++i)
89 r.push_back(i->first);
90 return r;
91 }
92
93 };
94}
95
96#endif
void registerType(const Type &t)
register type T for use with this factory
Definition factory.h:38
B * create(const Type &t) const
Create a default constructed object given by the type string.
Definition factory.h:75
std::vector< string > types() const
return list of registered types
Definition factory.h:85
void registerType()
convenience method for registering a type.
Definition factory.h:44
Contains definitions related to classdesc functionality.
Definition factory.h:63