]> git.localhorst.tv Git - blobs.git/blob - src/world/Set.hpp
af4d8a242959c166b95af639c6413bf8a81ff908
[blobs.git] / src / world / Set.hpp
1 #ifndef BLOBS_WORLD_SET_HPP_
2 #define BLOBS_WORLD_SET_HPP_
3
4 #include <map>
5 #include <stdexcept>
6 #include <string>
7 #include <vector>
8
9 namespace blobs {
10 namespace world {
11
12 template<class Type>
13 class Set {
14
15 public:
16         int Add(const Type &t) {
17                 int id = types.size();
18                 if (!names.emplace(t.name, id).second) {
19                         throw std::runtime_error("duplicate type name " + t.name);
20                 }
21                 types.emplace_back(t);
22                 types.back().id = id;
23                 return id;
24         }
25         bool Has(int id) const noexcept { return id < types.size(); }
26         bool Has(const std::string &name) const noexcept { return names.find(name) != names.end(); }
27
28         Type &operator [](int id) noexcept { return types[id]; }
29         const Type &operator [](int id) const noexcept { return types[id]; }
30
31         Type &operator [](const std::string &name) {
32                 auto entry = names.find(name);
33                 if (entry != names.end()) {
34                         return types[entry->second];
35                 } else {
36                         throw std::runtime_error("unknown type " + name);
37                 }
38         }
39         const Type &operator [](const std::string &name) const {
40                 auto entry = names.find(name);
41                 if (entry != names.end()) {
42                         return types[entry->second];
43                 } else {
44                         throw std::runtime_error("unknown type " + name);
45                 }
46         }
47
48 private:
49         std::vector<Type> types;
50         std::map<std::string, int> names;
51
52 };
53
54 }
55 }
56
57 #endif