20 #ifndef MIRTK_ObjectFactory_H 21 #define MIRTK_ObjectFactory_H 23 #include "mirtk/UnorderedMap.h" 24 #include "mirtk/Stream.h" 26 #include "mirtk/CommonExport.h" 33 MIRTK_Common_EXPORT
extern int debug;
40 template <
typename TId,
typename TInterface>
54 typedef Interface *(*Creator)();
82 typedef UnorderedMap<Id, Creator> TypeIdAssociations;
85 typedef UnorderedMap<const char *, Creator> TypeNameAssociations;
88 TypeIdAssociations _TypeIdAssociations;
91 TypeNameAssociations _TypeNameAssociations;
102 _TypeIdAssociations [type_id ] = creator;
103 _TypeNameAssociations[type_name] = creator;
105 cout <<
"Registered object type with name " << type_name <<
" and ID " << type_id << endl;
115 Interface *
New(Id type_id)
const 117 auto it = _TypeIdAssociations.find(type_id);
118 return (it == _TypeIdAssociations.end() ?
nullptr : (it->second)());
126 Interface *
New(
const char *type_name)
const 128 auto it = _TypeNameAssociations.find(type_name);
129 return (it == _TypeNameAssociations.end() ?
nullptr : (it->second)());
136 template <
class BaseType,
class ObjectType> BaseType *
New()
138 return new ObjectType();
143 #define mirtkDefineObjectFactory(id_type, base) \ 144 class base##Factory : public mirtk::ObjectFactory<id_type, base> \ 150 virtual ~base##Factory() {} \ 152 base##Factory(const base##Factory &); \ 154 void operator =(const base##Factory &); \ 157 static base##Factory &Instance() \ 159 static base##Factory instance; \ 166 #ifdef MIRTK_AUTO_REGISTER 167 #define mirtkAutoRegisterObjectTypeMacro(factory, id_type, id, base, type) \ 169 static auto _##type##Registered = \ 170 (factory).Register(id, type::NameOfType(), mirtk::New<base, type>); \ 172 #else // MIRTK_AUTO_REGISTER 173 #define mirtkAutoRegisterObjectTypeMacro(factory, id_type, id, base, type) 174 #endif // MIRTK_AUTO_REGISTER 179 #endif // MIRTK_ObjectFactory_H Interface * New(const char *type_name) const
TId Id
Type of object type identifier.
Interface * New(Id type_id) const
void operator=(const ObjectFactory &)
Assignment operator. Intentionally not implemented.
MIRTK_Common_EXPORT int debug
ObjectFactory()
Constructor.
TInterface Interface
Type of object base class.
Interface *(* Creator)()
Type of object creator.
bool Register(Id type_id, const char *type_name, Creator creator)
ObjectFactory< Id, Interface > InstanceType
Type of object factory instance.
virtual ~ObjectFactory()
Destructor.