EIC Software
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
PHGenericFactoryT.h
Go to the documentation of this file. Or view the newest version in sPHENIX GitHub for file PHGenericFactoryT.h
1 #ifndef PDBCAL_BASE_PHGENERICFACTORYT_H
2 #define PDBCAL_BASE_PHGENERICFACTORYT_H
3 
4 #include <iostream>
5 #include <map>
6 #include <string>
7 
22 template
23 <
24  class AbstractProduct
25 >
27 {
28 protected:
29  AbstractProduct* OnUnknownType(const std::string& /*id*/) { return 0; }
30 };
31 
32 template
33 <
34  class AbstractProduct,
35  template<class> class FactoryErrorPolicy = DefaultFactoryError
36 >
37 class PHGenericFactoryT : public FactoryErrorPolicy<AbstractProduct>
38 {
39 public:
40 
41  typedef AbstractProduct* (*ProductCreator)();
42  typedef std::string IdentifierType;
43 
45  {
46  public:
48  : creator_(), name_() {}
50  : creator_(creator),name_(productname) {}
51 
52  ProductCreator creator() const { return creator_; }
53  std::string productname() const { return name_; }
54 
55  private:
57  std::string name_;
58  };
59 
60 public:
61 
64  {
66  return factory;
67  }
68 
70  AbstractProduct* create(const char* id)
71  {
72  // the id parameter is a const char* instead of std::string
73  // just because we want to be able to access this one from
74  // ROOT prompt, and Cint seems to have some problems with
75  // std::string.
76 
77  typename CreatorMap::const_iterator it =
78  fCreators.find(IdentifierType(id));
79 
80  if ( it != fCreators.end() )
81  {
82  // invoke the creation function
83  return (it->second.creator())();
84  }
85 
86  // Upon failure we delegate to the FactoryError class
87  // that might simply returns 0 or try to e.g. load some more
88  // libs and retry, or whatever seems relevant to react
89  // to the error.
90 
91  return this->OnUnknownType(IdentifierType(id));
92  }
93 
95  void print(std::ostream& os = std::cout) const
96  {
97  typename CreatorMap::const_iterator it;
98  for ( it = fCreators.begin(); it != fCreators.end(); ++it )
99  {
100  os << "Creator id=" << it->first
101  << " for product " << it->second.productname()
102  << std::endl;
103  }
104  }
105 
108  ProductCreator creator,
109  const char* productname)
110  {
111  bool ok = fCreators.insert(typename CreatorMap::value_type(id,ProductCreatorPair(creator,productname))).second;
112 
113  if (!ok)
114  {
115  std::cerr << "PHGenericFactoryT::registerCreator : registry of creator "
116  << "id " << id << " for product " << productname
117  << "failed!" << std::endl;
118  }
119  else
120  {
121 #ifdef DEBUG
122  std::cout << "PHGenericFactoryT::registerCreator : creator id "
123  << id << " for product " << productname
124  << " registered." << std::endl;
125 #endif
126  }
127  return ok;
128  }
129 
132  {
133  return fCreators.erase(id) == 1;
134  }
135 
136 private:
137 
143 
144  typedef std::map<IdentifierType,ProductCreatorPair> CreatorMap;
146 };
147 
148 #endif