46 lines
1.3 KiB
C++
46 lines
1.3 KiB
C++
#pragma once
|
|
#include <string>
|
|
#include <unordered_map>
|
|
|
|
template <typename T>
|
|
class Registry {
|
|
public:
|
|
using ID = uint32_t; // Or uint16_t if fewer items expected
|
|
|
|
ID add(const std::string& name, T&& value) {
|
|
if (nameToId_.contains(name)) {
|
|
throw std::runtime_error("Duplicate registration: " + name);
|
|
}
|
|
ID id = static_cast<ID>(entries.size());
|
|
entries.push_back(std::move(value));
|
|
nameToId_[name] = id;
|
|
idToName_[id] = name;
|
|
return id;
|
|
}
|
|
|
|
const T& get(ID id) const {
|
|
if (id >= entries.size()) throw std::out_of_range("Invalid ID");
|
|
return entries[id];
|
|
}
|
|
|
|
ID getID(const std::string& name) const {
|
|
auto it = nameToId_.find(name);
|
|
if (it == nameToId_.end()) throw std::runtime_error("Unknown name: " + name);
|
|
return it->second;
|
|
}
|
|
|
|
const std::string& getName(ID id) const {
|
|
auto it = idToName_.find(id);
|
|
if (it == idToName_.end()) throw std::out_of_range("Invalid ID");
|
|
return it->second;
|
|
}
|
|
|
|
// Optional: Iteration over all entries
|
|
const std::vector<T>& all() const { return entries; }
|
|
|
|
private:
|
|
std::vector<T> entries;
|
|
std::unordered_map<std::string, ID> nameToId_;
|
|
std::unordered_map<ID, std::string> idToName_; // For reverse lookup
|
|
};
|
|
|