Alsvinn  0.5.3
The fast FVM simulator with UQ support
FactoryRegistry.hpp
Go to the documentation of this file.
1 #pragma once
2 #include <memory>
3 #include <functional>
4 #include <string>
5 #include <map>
7 
8 
9 namespace alsutils {
10 namespace base {
11 namespace impl {
12 
22 template<class T, class ... Args>
24 private:
25  // singleton and non-copyable
26  FactoryRegistry() {}
27  FactoryRegistry(const FactoryRegistry& other) {}
28 public:
29 
30  typedef std::shared_ptr<T> PointerType;
31  typedef std::function<PointerType(Args...)> CreatorType;
32 
36  bool registerClass(const std::string& name,
37  CreatorType creator) {
38  if (creators.find(name) != creators.end()) {
39  THROW("Class named " << name << " for base class " <<
40  T::getClassName() << " already registered with the factory.");
41  }
42 
43  creators[name] = creator;
44  return true;
45  }
46 
50  template<class C>
51  bool registerClassWithOnlyConstructor(const std::string& name) {
52  auto constructor = [&](Args... args) {
53  PointerType pointer;
54  pointer.reset(new C(args...));
55  return pointer;
56  };
57  return registerClass(name, constructor);
58  }
59 
60 
62  PointerType createInstance(const std::string& name, Args... args) {
63  if (creators.find(name) == creators.end()) {
64  THROW("Could not find class named " << name << " for base class " <<
65  T::getClassName());
66  }
67 
68  return creators[name](args...);
69  }
70 
73  static FactoryRegistry factory;
74  return factory;
75  }
76 private:
77  std::map<std::string, CreatorType> creators;
78 };
79 } // namespace impl
80 } // namespace base
81 } // namespace alsutils
bool registerClass(const std::string &name, CreatorType creator)
Definition: FactoryRegistry.hpp:36
Definition: FactoryRegistry.hpp:23
PointerType createInstance(const std::string &name, Args... args)
Creates a new instance of the class with the given name and arguments.
Definition: FactoryRegistry.hpp:62
std::shared_ptr< T > PointerType
Definition: FactoryRegistry.hpp:30
#define THROW(message)
Definition: Exception.hpp:27
std::function< PointerType(Args...)> CreatorType
Definition: FactoryRegistry.hpp:31
std::string name
Definition: EquationParameterFactory.cpp:39
Various utilities for mpi and cuda.
Definition: Factory.hpp:3
static FactoryRegistry & getInstance()
Gets the singleton instance of this class.
Definition: FactoryRegistry.hpp:72
bool registerClassWithOnlyConstructor(const std::string &name)
Definition: FactoryRegistry.hpp:51