]> git.localhorst.tv Git - blobs.git/blob - src/world/Set.hpp
fun with resources
[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
26         Type &operator [](int id) noexcept { return types[id]; }
27         const Type &operator [](int id) const noexcept { return types[id]; }
28
29         Type &operator [](const std::string &name) {
30                 auto entry = names.find(name);
31                 if (entry != names.end()) {
32                         return types[entry->second];
33                 } else {
34                         throw std::runtime_error("unknown type " + name);
35                 }
36         }
37         const Type &operator [](const std::string &name) const {
38                 auto entry = names.find(name);
39                 if (entry != names.end()) {
40                         return types[entry->second];
41                 } else {
42                         throw std::runtime_error("unknown type " + name);
43                 }
44         }
45
46 private:
47         std::vector<Type> types;
48         std::map<std::string, int> names;
49
50 };
51
52 }
53 }
54
55 #endif