ifw-sup  2.1.0-pre1
subsysFactory.hpp
Go to the documentation of this file.
1 
9 #ifndef SUP_SYSSUP_COMMON_SUBSYSFACTORY_HPP
10 #define SUP_SYSSUP_COMMON_SUBSYSFACTORY_HPP
11 
12 // System headers
13 #include <iostream>
14 #include <memory>
15 #include <string>
16 #include <unordered_map>
17 
18 #include <cstdlib>
19 #include <cxxabi.h>
20 
21 namespace sup::syssup::common {
22 
23 std::string Demangle(const char *name);
24 
34  template <class Base, class... Args> class Factory {
35  public:
36 
37  template <class ... T>
46  static std::unique_ptr<Base> Create(const std::string &s, T&&... args) {
47  const auto& obj_map = Data();
48  auto i = obj_map.find(s);
49  if (i == obj_map.end()) {
50  return nullptr;
51  } else {
52  return obj_map.at(s)(std::forward<T>(args)...);
53  }
54  }
55 
56  template <class T> struct Registrar : Base {
57  friend T;
58 
59  static bool RegisterT() {
60  const auto name = sup::syssup::common::Demangle(typeid(T).name());
61 
62  Factory::Data()[name] = [](Args... args) -> std::unique_ptr<Base> {
63  return std::make_unique<T>(std::forward<Args>(args)...);
64  };
65  return true;
66  }
67  static bool registered;
68 
69  private:
70  Registrar() : Base(Key{}) { (void)registered; }
71  };
72 
73  friend Base;
74 
75  private:
76  class Key {
77  Key(){};
78  template <class T> friend struct Registrar;
79  };
80  using FuncType = std::unique_ptr<Base> (*)(Args...);
81  Factory() = default;
82 
83  static auto &Data() {
84  static std::unordered_map<std::string, FuncType> s;
85  return s;
86  }
87  };
88 
89  template <class Base, class... Args>
90  template <class T>
91  bool Factory<Base, Args...>::Registrar<T>::registered =
93 
94 }
95 
96 #endif //SUP_SYSSUP_COMMON_SUBSYS_FACTORY_HPP
sup::syssup::common::Factory::Registrar
Definition: subsysFactory.hpp:56
sup::syssup::common::Factory
Definition: subsysFactory.hpp:34
sup::syssup::common::Factory::Registrar::registered
static bool registered
Definition: subsysFactory.hpp:67
sup::syssup::common::Factory::Registrar::RegisterT
static bool RegisterT()
Definition: subsysFactory.hpp:59
sup::syssup::common
Definition: actionMgr.cpp:31
sup::syssup::common::Factory::Create
static std::unique_ptr< Base > Create(const std::string &s, T &&... args)
create subsystem object instance
Definition: subsysFactory.hpp:46
sup::syssup::common::Demangle
std::string Demangle(const char *name)
Definition: subsysFactory.cpp:15
sup::syssup::common::Factory::Base
friend Base
Definition: subsysFactory.hpp:73
sup::syssup::common::Factory::Registrar::T
friend T
Definition: subsysFactory.hpp:57