RobinTrace
type_map.h
Go to the documentation of this file.
1 
2 #ifndef TYPE_MAP_H
3 #define TYPE_MAP_H
4 
5 #include <unordered_map>
6 #include <memory>
7 #include <typeindex>
8 
10 template <class element_type>
11 class type_map {
12  private:
14  std::unordered_map<std::type_index, std::unique_ptr<element_type>> table;
15  public:
17  template <typename T>
18  void add (const T &input) {
19  static_assert(std::is_base_of<element_type, T>::value,
20  "T must be derived from element_type.");
21  table[std::type_index(typeid(T))] = std::make_unique<T>(input);
22  }
23 
25  template <typename T>
26  T& get () {
27  static_assert(std::is_base_of<element_type, T>::value,
28  "T must be derived from element_type.");
29  auto it = table.find(std::type_index(typeid(T)));
30  if (it != table.end()) {
31  return *static_cast<T*>(it->second.get());
32  } else {
33  throw std::runtime_error("Element type not found.");
34  }
35  }
36 };
37 
38 #endif // TYPE_MAP_H
Map class storing unique_ptr to elements and keyed by their type.
Definition: type_map.h:11
T & get()
Get a reference to an element of the map.
Definition: type_map.h:26
std::unordered_map< std::type_index, std::unique_ptr< element_type > > table
Map of type/pointers.
Definition: type_map.h:14
void add(const T &input)
Add an element of a type derived from element_type.
Definition: type_map.h:18