5 #include <unordered_map>
10 template <
class element_type>
14 std::unordered_map<std::type_index, std::unique_ptr<element_type>>
table;
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);
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());
33 throw std::runtime_error(
"Element type not found.");
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