/home/docs/checkouts/readthedocs.org/user_builds/ratpac/checkouts/latest/src/fit/mimir/include/mimir/Factory.hh Source File

Ratpac-two: /home/docs/checkouts/readthedocs.org/user_builds/ratpac/checkouts/latest/src/fit/mimir/include/mimir/Factory.hh Source File
Ratpac-two
Factory.hh
1 #pragma once
2 #include <RAT/DB.hh>
3 #include <RAT/Log.hh>
4 #include <functional>
5 #include <map>
6 #include <memory>
7 #include <mimir/Common.hh>
8 
9 // Generic factory for all MIMIR components.
10 namespace Mimir {
11 
12 template <typename Base>
13 class Factory {
14  public:
15  using MakeFunc = std::function<std::unique_ptr<Base>()>;
16 
17  static Factory& GetInstance() {
18  static Factory theInstance;
19  return theInstance;
20  }
21 
22  void register_type(const std::string& name, MakeFunc mf) { registry_map[name] = mf; }
23 
24  std::unique_ptr<Base> make(const std::string& type_name) const {
25  auto it = registry_map.find(type_name);
26  if (it == registry_map.end()) {
27  RAT::Log::Die("[MIMIR Factory] Unknown type: " + type_name);
28  }
29  return it->second();
30  }
31 
32  std::unique_ptr<Base> make_and_configure(const std::string& type_name, const std::string& config_name) const {
33  std::unique_ptr<Base> instance = make(type_name);
34  RAT::DBLinkPtr db_link = GetConfig(type_name, config_name);
35  instance->SetName(GetConfigRepr(db_link));
36  RAT::info << "[MIMIR Factory] Configuring instance: " << instance->GetName() << newline;
37  if (!instance->Configure(db_link)) {
38  RAT::Log::Die("[MIMIR Factory] Failed to configure instance: " + instance->GetName());
39  }
40  return instance;
41  }
42 
43  private:
44  std::map<std::string, MakeFunc> registry_map;
45 };
46 
47 } // namespace Mimir
48 
49 namespace Mimir::detail {
50 // Helper object to keep track of class registration with a template
51 template <class Base, class Derived>
52 struct AutoRegistrar {
53  static const bool registered;
54 };
55 } // namespace Mimir::detail
56 
57 #define MIMIR_REGISTER_TYPE(BaseType, DerivedType, type_name) \
58  namespace Mimir::detail { \
59  template <> \
60  const bool AutoRegistrar<BaseType, DerivedType>::registered = [] { \
61  Mimir::Factory<BaseType>::GetInstance().register_type(type_name, [] { return std::make_unique<DerivedType>(); }); \
62  return true; \
63  }(); \
64  }
Definition: Factory.hh:13
static void Die(std::string message, int return_code=1)
Definition: Log.cc:90
Definition: Factory.hh:52