RTC Toolkit  0.1.0-alpha
serviceContainer.hpp
Go to the documentation of this file.
1 
9 #ifndef RTCTK_COMPONENTFRAMEWORK_SERVICECONTAINER_HPP
10 #define RTCTK_COMPONENTFRAMEWORK_SERVICECONTAINER_HPP
11 
12 #include <string>
13 #include <vector>
14 #include <map>
15 #include <utility>
16 #include <any>
17 #include <memory>
18 
19 namespace rtctk::componentFramework {
20 
31 {
32 public:
33 
44  template <typename Service>
45  void Add(Service&& service, const std::string& name = "") {
46  std::string key = CalcMapKey(typeid(Service), name);
47  if(MapContains(key)) {
48  throw std::runtime_error("service '" + key + "' already registered");
49  }
50  m_services.emplace(key, std::make_pair(std::forward<Service>(service), false));
51  }
52 
63  template <typename Service>
64  void Add(std::shared_ptr<Service> service, const std::string& name = "") {
65  std::string key = CalcMapKey(typeid(Service), name);
66  if(MapContains(key)) {
67  throw std::runtime_error("service '" + key + "' already registered");
68  }
69  m_services.emplace(key, std::make_pair(service, true));
70  }
71 
81  template <typename Service>
82  Service& Get(const std::string& name = "") {
83  std::string key = CalcMapKey(typeid(Service), name);
84  if(not MapContains(key)) {
85  throw std::runtime_error("service '" + key + "' not registered");
86  }
87  if(ServiceIsHeldByPointer(key)) {
88  return *std::any_cast<std::shared_ptr<Service>>(m_services[key].first);
89  }else {
90  return std::any_cast<Service&>(m_services[key].first);
91  }
92  }
93 
102  template <typename Service>
103  bool Contains(const std::string& name = "") {
104  return MapContains(CalcMapKey(typeid(Service), name));
105  }
106 
112  std::vector<std::string> List();
113 
114 private:
115 
116  std::string CalcMapKey(const std::type_info& tid, const std::string& name);
117 
118  bool MapContains(const std::string& key);
119  bool ServiceIsHeldByPointer(const std::string& key);
120 
121  // string:key, any:service, bool:true if services is held by a pointer
122  std::map<std::string, std::pair<std::any, bool>> m_services;
123 };
124 
125 } // closing namespace
126 
127 #endif
rtctk::componentFramework::ServiceContainer::Get
Service & Get(const std::string &name="")
Definition: serviceContainer.hpp:82
rtctk::componentFramework::ServiceContainer::Add
void Add(Service &&service, const std::string &name="")
Definition: serviceContainer.hpp:45
rtctk::componentFramework
Definition: rtcComponent.hpp:17
rtctk::componentFramework::ServiceContainer::Add
void Add(std::shared_ptr< Service > service, const std::string &name="")
Definition: serviceContainer.hpp:64
rtctk::componentFramework::ServiceContainer::List
std::vector< std::string > List()
Definition: serviceContainer.cpp:6
rtctk::componentFramework::ServiceContainer
Definition: serviceContainer.hpp:31
rtctk::componentFramework::ServiceContainer::Contains
bool Contains(const std::string &name="")
Definition: serviceContainer.hpp:103