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 ) \
11 std::string DERIVED_CLASS::_id = AmpGen::Factory<BASE_CLASS>::Register( #DERIVED_CLASS, new DERIVED_CLASS() )
12#define REGISTER_WITH_KEY( BASE_CLASS, DERIVED_CLASS, KEY, KEY_TYPE ) \
13 KEY_TYPE DERIVED_CLASS::_id = AmpGen::Factory<BASE_CLASS, KEY_TYPE>::Register( KEY, new DERIVED_CLASS() )
14
15namespace AmpGen
16{
20 template <class TYPE, class KEY_TYPE = std::string>
21 class Factory
22 {
23 public:
24 std::map<KEY_TYPE, TYPE*> m_terms;
26
28 {
29 if ( !gImpl ) gImpl = new Factory<TYPE, KEY_TYPE>();
30 return gImpl;
31 }
32 static TYPE* get( const KEY_TYPE& type, const bool quiet = false )
33 {
34 auto ptrToStatic = getMe();
35 auto raw_base = ptrToStatic->m_terms.find( type );
36 if ( raw_base == ptrToStatic->m_terms.end() ) {
37 if ( !quiet ) ERROR( type << " not found in Factory<" << type_string<TYPE>() << type_string<KEY_TYPE>() << " >" );
38 return nullptr;
39 }
40 auto objectToReturn = raw_base->second->create();
41 return objectToReturn;
42 }
43 static KEY_TYPE Register( const KEY_TYPE& key, TYPE* object )
44 {
45 getMe()->m_terms[key] = object;
46 return key;
47 }
48 };
49
50 template <class TYPE, class KEY_TYPE>
52} // namespace AmpGen
53
54#endif
55
Static factory to construct classes from a hierarchy based on a key (normally std::string)
Definition Factory.h:22
static Factory< TYPE, KEY_TYPE > * getMe()
Definition Factory.h:27
static TYPE * get(const KEY_TYPE &type, const bool quiet=false)
Definition Factory.h:32
static Factory< TYPE, KEY_TYPE > * gImpl
pointer to static implementation
Definition Factory.h:25
static KEY_TYPE Register(const KEY_TYPE &key, TYPE *object)
Definition Factory.h:43
std::map< KEY_TYPE, TYPE * > m_terms
map of objected made by this factory
Definition Factory.h:24
#define ERROR(X)
Used for printing errors messages, and will always be printed.
Definition MsgService.h:80
std::string type_string()
Utility classes for compile-time metaprogramming, such as identifying the types of arguments for gene...
Definition MetaUtils.h:18