Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Released under the CC0 1.0 Universal license.
- #include <map>
- #include <mutex>
- #include <string>
- #include <typeindex>
- class ContextContainer {
- using Self = ContextContainer;
- public:
- ContextContainer() {}
- ~ContextContainer() {}
- ContextContainer(const Self& rhs) = delete;
- Self& operator=(const Self& rhs) = delete;
- ContextContainer(Self&& rhs) : map_(std::move(rhs.map_)) {}
- Self& operator=(Self&& rhs)
- {
- if (this != &rhs) {
- this->Swap(rhs);
- }
- return *this;
- }
- void Swap(Self& rhs)
- {
- using std::swap;
- swap(map_, rhs.map_);
- }
- template <typename T, typename... Args>
- T* Create(const std::string& key, Args&&... args)
- {
- std::unique_lock<std::mutex> lock(mutex_);
- std::shared_ptr<T> ptr = std::make_shared<T>(std::forward<Args>(args)...);
- T* result = ptr.get();
- map_[{typeid(T), key}] = std::move(ptr);
- return result;
- }
- template <typename T>
- const T* Get(const std::string& key) const
- {
- std::unique_lock<std::mutex> lock(mutex_);
- auto it = map_.find({typeid(T), key});
- if (it == map_.end()) {
- return nullptr;
- }
- return reinterpret_cast<T*>(it->second.get());
- }
- template <typename T>
- void Destroy(const std::string& key) noexcept
- {
- std::unique_lock<std::mutex> lock(mutex_);
- map_.erase({typeid(T), key});
- }
- private:
- struct Key {
- std::type_index type_index;
- std::string key;
- bool operator<(const Key& rhs) const
- {
- return type_index < rhs.type_index || (type_index == rhs.type_index && key < rhs.key);
- }
- };
- std::map<Key, std::shared_ptr<void>> map_;
- mutable std::mutex mutex_;
- };
- #include <iostream>
- #include <cstdlib>
- #define PRINT(e) std::cout << #e ": " << (e) << std::endl
- int main()
- {
- std::cout << "Hello, Wandbox!" << std::endl;
- ContextContainer c1;
- c1.Create<int>("i", 123);
- PRINT(*c1.Get<int>("i"));
- c1.Create<int>("j", 456);
- PRINT(*c1.Get<int>("j"));
- c1.Create<double>("i", 3.14);
- PRINT(*c1.Get<double>("i"));
- PRINT(c1.Get<double>("j"));
- c1.Create<int>("j", 789);
- PRINT(*c1.Get<int>("j"));
- c1.Destroy<int>("j");
- PRINT(c1.Get<int>("j"));
- ContextContainer c2 = std::move(c1);
- PRINT(c1.Get<int>("i"));
- PRINT(*c2.Get<int>("i"));
- PRINT(*c2.Get<double>("i"));
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement