AmpGen 2.1
Loading...
Searching...
No Matches
Factory.h
Go to the documentation of this file.
1#ifndef AMPGEN_FACTORY_H
2#define AMPGEN_FACTORY_H
3
4#include <cxxabi.h>
5#include <map>
6
7#include "AmpGen/MsgService.h"
8#include "AmpGen/Utilities.h"
9
10#define REGISTER(BASE_CLASS, DERIVED_CLASS) std::string DERIVED_CLASS::_id = AmpGen::Factory<BASE_CLASS>::Register(#DERIVED_CLASS, new DERIVED_CLASS())
11#define REGISTER_WITH_KEY(BASE_CLASS, DERIVED_CLASS, KEY, KEY_TYPE) \
12 KEY_TYPE DERIVED_CLASS::_id = AmpGen::Factory<BASE_CLASS, KEY_TYPE>::Register(KEY, new DERIVED_CLASS())
13
14namespace AmpGen {
18 template <class TYPE, class KEY_TYPE = std::string> class Factory {
19 public:
20 std::map<KEY_TYPE, TYPE *> m_terms;
22
25 return gImpl;
26 }
27 static TYPE *get(const KEY_TYPE &type, const bool quiet = false) {
28 auto ptrToStatic = getMe();
29 auto raw_base = ptrToStatic->m_terms.find(type);
30 if(raw_base == ptrToStatic->m_terms.end()) {
31 if(!quiet) ERROR(type << " not found in Factory<" << type_string<TYPE>() << type_string<KEY_TYPE>() << " >");
32 return nullptr;
33 }
34 auto objectToReturn = raw_base->second->create();
35 return objectToReturn;
36 }
37 static KEY_TYPE Register(const KEY_TYPE &key, TYPE *object) {
38 getMe()->m_terms[key] = object;
39 return key;
40 }
41 };
42
43 template <class TYPE, class KEY_TYPE> Factory<TYPE, KEY_TYPE> *Factory<TYPE, KEY_TYPE>::gImpl = nullptr;
44} // namespace AmpGen
45
46#endif
Static factory to construct classes from a hierarchy based on a key (normally std::string).
Definition Factory.h:18
static Factory< TYPE, KEY_TYPE > * getMe()
Definition Factory.h:23
static TYPE * get(const KEY_TYPE &type, const bool quiet=false)
Definition Factory.h:27
static Factory< TYPE, KEY_TYPE > * gImpl
pointer to static implementation
Definition Factory.h:21
static KEY_TYPE Register(const KEY_TYPE &key, TYPE *object)
Definition Factory.h:37
std::map< KEY_TYPE, TYPE * > m_terms
map of objected made by this factory
Definition Factory.h:20
#define ERROR(X)
Used for printing errors messages, and will always be printed.
Definition MsgService.h:85
std::string type_string()
Utility classes for compile-time metaprogramming, such as identifying the types of arguments for gene...
Definition MetaUtils.h:17