Created
February 4, 2025 12:15
-
-
Save Shtille/672f76dff95697ea0ce22faf04f19b80 to your computer and use it in GitHub Desktop.
Cache for data to be shared between different instances
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <map> | |
#include <memory> | |
template <class Key, class Data> | |
class DataCache | |
{ | |
public: | |
template<typename... Args> | |
std::shared_ptr<Data> GetData(const Key& key, Args... args) | |
{ | |
auto it = map_.find(key); | |
if (it != map_.end()) | |
if (auto data = it->second.lock()) | |
return data; | |
auto data = std::make_shared<Data>(args...); | |
map_[key] = data; | |
return data; | |
} | |
private: | |
std::map<Key, std::weak_ptr<Data> > map_; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment