Classdesc  3.D29
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 FACTORY_H
10 #define FACTORY_H
11 #include "classdesc.h"
12 #include "error.h"
13 #include <sstream>
14 
15 namespace classdesc
16 {
19  template <class B, class Type>
20  class Factory
21  {
22  struct CreatorBase
23  {
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  }
44  template <class T> void registerType()
45  {registerType<T>(T().type());}
46 
47 
60  Factory();
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
std::vector< string > types() const
return list of registered types
Definition: factory.h:85
B * create(const Type &t) const
Create a default constructed object given by the type string.
Definition: factory.h:75
void registerType(const Type &t)
register type T for use with this factory
Definition: factory.h:38
void registerType()
convenience method for registering a type.
Definition: factory.h:44
Definition: factory.h:62
base class for exceptions thrown by classdesc
Definition: classdesc.h:391
Definition: factory.h:20