Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Run online at https://repl.it/repls/ShadyMajesticOcelot
- #include <iostream>
- #include <string>
- #include <unordered_map>
- #include <memory>
- class Base
- {
- public:
- virtual ~Base() = default;
- };
- class Player
- {
- public:
- template<class T> T* Get(std::string const & k) const {
- static_assert(std::is_base_of<Base, T>::value, "T must derive from Base");
- auto it = cont.find(k);
- if (it != cont.end())
- return dynamic_cast<T*>(it->second.get());
- return nullptr;
- }
- void Set(std::string const & k, Base* v) { cont[k] = std::unique_ptr<Base>(v); }
- private:
- std::unordered_map<std::string, std::unique_ptr<Base>> cont;
- };
- class Test : public Base
- {
- public:
- Test(std::string const & str) : str(str) {}
- std::string str;
- };
- class Bad
- {
- public:
- Bad(std::string const & str) : str(str) {}
- std::string str;
- };
- int main() {
- Player p;
- Player* player = &p;
- // Example usage
- player->Set("asd", new Test("Example"));
- if (Test* test = player->Get<Test>("asd"))
- std::cout << test->str << std::endl;
- player->Set("Base", new Base());
- if (Base* base = player->Get<Base>("Base"))
- std::cout << "Base works too" << std::endl;
- // Bad class example
- // player->Set("bad", new Bad("Bad")); // does not compile, not derived from Base
- // Bad* bad = player->Get<Bad>("bad"); // does not compile, not derived from Base
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement