File generic_factory.hxx

Defines

__BOUT_GENERIC_FACTORY_H__
template<typename BaseType, typename TypeCreator = std::function<BaseType *()>>
class Factory
#include <generic_factory.hxx>

Generic Factory, adapted from Modern C++ Design/Loki by A. Alexandrescu

Use with RegisterInFactory to provide a generic way of creating new derived types at runtime

Example:

class Base {};
class Derived : public Base {};
RegisterInFactory<Base, Derived> register("derived_type");
auto foo = Factory<Base>::getInstance().create("derived_type");

TODO: Use std::unique_ptr<BaseType> instead of BaseType*

MIT Licence

Template Parameters
  • BaseType: The base class that this factory creates
  • TypeCreator: The function signature for creating a new BaseType

Public Functions

virtual bool add(const std::string &name, TypeCreator creator)

Add a new type name to the factory

Return
true if the type was successfully added
Parameters
  • name: An identifier for this type
  • creator: A function for creating this type

virtual bool remove(const std::string &name)

Remove a type name from the factory

Return
true if the type was successfully removed
Parameters
  • name: The identifier for the type to be removed

template<typename ...Args>
BaseType *create(const std::string &name, Args&&... args)

Create a new object of type name

Return
a pointer to the new object
Parameters
  • name: The identifier for the type to be created

virtual std::vector<std::string> listAvailable()

List available types that can be created

Return
a vector of std::string

Public Static Functions

static Factory &getInstance()

Get the singleton instance.

Protected Functions

Factory()

Protected Attributes

std::map<std::string, TypeCreator> type_map
template<typename BaseType, typename DerivedType>
class RegisterInFactory
#include <generic_factory.hxx>

Helper class for adding new types to Factory

Example:

class Base {};
class Derived : public Base {};
RegisterInFactory<Base, Derived> register("derived_type");
auto foo = Factory<Base>::getInstance().create("derived_type");

Adapted from http://www.drdobbs.com/conversations-abstract-factory-template/184403786

Template Parameters
  • BaseType: Which factory to add DerivedType to
  • DerivedType: The new type to add to Factory<BaseType>

Public Functions

RegisterInFactory(const std::string &name)