Advertisement
Guest User

Untitled

a guest
Apr 23rd, 2017
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.40 KB | None | 0 0
  1. // Released under the CC0 1.0 Universal license.
  2. #include <map>
  3. #include <mutex>
  4. #include <string>
  5. #include <typeindex>
  6.  
  7. class ContextContainer {
  8. using Self = ContextContainer;
  9.  
  10. public:
  11. ContextContainer() {}
  12. ~ContextContainer() {}
  13. ContextContainer(const Self& rhs) = delete;
  14. Self& operator=(const Self& rhs) = delete;
  15. ContextContainer(Self&& rhs) : map_(std::move(rhs.map_)) {}
  16. Self& operator=(Self&& rhs)
  17. {
  18. if (this != &rhs) {
  19. this->Swap(rhs);
  20. }
  21. return *this;
  22. }
  23. void Swap(Self& rhs)
  24. {
  25. using std::swap;
  26. swap(map_, rhs.map_);
  27. }
  28. template <typename T, typename... Args>
  29. T* Create(const std::string& key, Args&&... args)
  30. {
  31. std::unique_lock<std::mutex> lock(mutex_);
  32. std::shared_ptr<T> ptr = std::make_shared<T>(std::forward<Args>(args)...);
  33. T* result = ptr.get();
  34. map_[{typeid(T), key}] = std::move(ptr);
  35. return result;
  36. }
  37. template <typename T>
  38. const T* Get(const std::string& key) const
  39. {
  40. std::unique_lock<std::mutex> lock(mutex_);
  41. auto it = map_.find({typeid(T), key});
  42. if (it == map_.end()) {
  43. return nullptr;
  44. }
  45. return reinterpret_cast<T*>(it->second.get());
  46. }
  47. template <typename T>
  48. void Destroy(const std::string& key) noexcept
  49. {
  50. std::unique_lock<std::mutex> lock(mutex_);
  51. map_.erase({typeid(T), key});
  52. }
  53.  
  54. private:
  55. struct Key {
  56. std::type_index type_index;
  57. std::string key;
  58. bool operator<(const Key& rhs) const
  59. {
  60. return type_index < rhs.type_index || (type_index == rhs.type_index && key < rhs.key);
  61. }
  62. };
  63. std::map<Key, std::shared_ptr<void>> map_;
  64. mutable std::mutex mutex_;
  65. };
  66.  
  67. #include <iostream>
  68. #include <cstdlib>
  69. #define PRINT(e) std::cout << #e ": " << (e) << std::endl
  70.  
  71. int main()
  72. {
  73. std::cout << "Hello, Wandbox!" << std::endl;
  74. ContextContainer c1;
  75. c1.Create<int>("i", 123);
  76. PRINT(*c1.Get<int>("i"));
  77. c1.Create<int>("j", 456);
  78. PRINT(*c1.Get<int>("j"));
  79. c1.Create<double>("i", 3.14);
  80. PRINT(*c1.Get<double>("i"));
  81. PRINT(c1.Get<double>("j"));
  82. c1.Create<int>("j", 789);
  83. PRINT(*c1.Get<int>("j"));
  84. c1.Destroy<int>("j");
  85. PRINT(c1.Get<int>("j"));
  86. ContextContainer c2 = std::move(c1);
  87. PRINT(c1.Get<int>("i"));
  88. PRINT(*c2.Get<int>("i"));
  89. PRINT(*c2.Get<double>("i"));
  90. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement