Advertisement
Rochet2

Data storage c++

Dec 29th, 2017
336
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.39 KB | None | 0 0
  1. // Run online at https://repl.it/repls/ShadyMajesticOcelot
  2.  
  3. #include <iostream>
  4. #include <string>
  5. #include <unordered_map>
  6. #include <memory>
  7.  
  8. class Base
  9. {
  10. public:
  11.   virtual ~Base() = default;
  12. };
  13.  
  14. class Player
  15. {
  16. public:
  17.   template<class T> T* Get(std::string const & k) const {
  18.     static_assert(std::is_base_of<Base, T>::value, "T must derive from Base");
  19.     auto it = cont.find(k);
  20.     if (it != cont.end())
  21.       return dynamic_cast<T*>(it->second.get());
  22.     return nullptr;
  23.   }
  24.   void Set(std::string const & k, Base* v) { cont[k] = std::unique_ptr<Base>(v); }
  25. private:
  26.   std::unordered_map<std::string, std::unique_ptr<Base>> cont;
  27. };
  28.  
  29. class Test : public Base
  30. {
  31. public:
  32.   Test(std::string const & str) : str(str) {}
  33.   std::string str;
  34. };
  35.  
  36. class Bad
  37. {
  38. public:
  39.   Bad(std::string const & str) : str(str) {}
  40.   std::string str;
  41. };
  42.  
  43. int main() {
  44.   Player p;
  45.   Player* player = &p;
  46.  
  47.   // Example usage
  48.   player->Set("asd", new Test("Example"));
  49.   if (Test* test = player->Get<Test>("asd"))
  50.     std::cout << test->str << std::endl;
  51.    
  52.   player->Set("Base", new Base());
  53.   if (Base* base = player->Get<Base>("Base"))
  54.     std::cout << "Base works too" << std::endl;
  55.  
  56.   // Bad class example
  57.   // player->Set("bad", new Bad("Bad")); // does not compile, not derived from Base
  58.   // Bad* bad = player->Get<Bad>("bad"); // does not compile, not derived from Base
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement