25 #ifndef SRC_CORE_INCLUDE_CORBO_CORE_FACTORY_H_ 26 #define SRC_CORE_INCLUDE_CORBO_CORE_FACTORY_H_ 33 #include <type_traits> 34 #include <unordered_map> 67 template <
typename Base>
92 template <
typename Derived = Base>
93 std::shared_ptr<Derived>
create(
const std::string& name,
bool print_error =
true)
const 95 static_assert(std::is_base_of<Base, Derived>::value,
"Factory::create(): specified dervied class type is an actual subclass of base.");
100 PRINT_ERROR_COND(print_error,
"Factory<" <<
typeid(Base).name() <<
">::create():: unkown object '" << name <<
"'.");
101 return std::shared_ptr<Derived>();
104 std::shared_ptr<Derived> derived_ptr = std::dynamic_pointer_cast<Derived>(obj->second->getInstance());
105 PRINT_ERROR_COND(!derived_ptr && print_error,
"Factory::create():: cannot cast base object " <<
typeid(Base).name() <<
" to derived object " 106 <<
typeid(Derived).name() <<
".");
132 std::unordered_map<std::string, std::shared_ptr<Base>>
_object_map;
135 #define FACTORY_REGISTER_OBJECT_ID(type, base, id) \ 136 static const bool corbo_CAT(corbo_CAT(type, __regged), id) = \ 137 Factory<base>::instance().registerObject(corbo_STRINGIZE(type), std::make_shared<type>()); 139 #define FACTORY_REGISTER_OBJECT(type, base) FACTORY_REGISTER_OBJECT_ID(type, base, 0) 149 template <
typename Object>
152 return Object::getFactory().template create<Object>(name);
157 #endif // SRC_CORE_INCLUDE_CORBO_CORE_FACTORY_H_ bool registerObject(const std::string &name, std::shared_ptr< Base > object_type)
Register a new object.
#define PRINT_ERROR_COND(cond, msg)
Print msg-stream only if cond == true.
const std::unordered_map< std::string, std::shared_ptr< Base > > & getObjectMap() const
bool hasObject(const std::string &name)
Check if a specified object (name) has been registered.
std::shared_ptr< Object > create_from_factory(const std::string &name)
Helper function to create new (derived) objects from factory.
static Factory & instance()
< Retrieve static instance of the factory
std::unordered_map< std::string, std::shared_ptr< Base > > _object_map
map of identifiers and their corresponding objects (default-constructed)
std::shared_ptr< Derived > create(const std::string &name, bool print_error=true) const
Create a shared instance of the desired object.
void printObjects() const
Print registered object names to console.
#define PRINT_INFO(msg)
Print msg-stream.