Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- template<typename DataValue>
- class Cache {
- private:
- class Data {
- public:
- DataValue dataValue;
- std::list<std::string>::iterator it;
- Data(const DataValue& dataValue, std::list<std::string>::iterator newIterator)
- : dataValue(dataValue)
- , it(newIterator)
- {}
- Data() {}
- };
- std::unordered_map<std::string, Data> map;
- std::list<std::string> listOfKeys;
- std::function<DataValue(std::string)> GetFromServer;
- int MAX_SIZE;
- void RemoveMostNotRelevant() {
- const std::string& mostNotRelevantKey = listOfKeys.front();
- map.erase(mostNotRelevantKey);
- listOfKeys.pop_front();
- }
- public:
- Cache(int maxSize = 1, std::function<DataValue(std::string)> getFromServer)
- : MAX_SIZE(maxSize)
- , GetFromServer(getFromServer)
- {}
- Data operator () (const std::string& key) {
- if (std::size(map) == MAX_SIZE) {
- if (map.count(key)) {
- Data& data = map[key];
- listOfKeys.erase(data.it);
- listOfKeys.push(key);
- data.it = std::prev(listOfKeys.end());
- return data.dataValue;
- } else {
- RemoveMostNotRelevant();
- DataValue dataValue = GetFromServer(key);
- listOfKeys.push(key);
- Data data(dataValue, std::prev(listOfKeys.end()));
- map[key] = data;
- return dataValue;
- }
- } else {
- auto [it, inserted] = map.insert({key, Data()});
- Data& data = it->second;
- if (inserted) {
- data.dataValue = GetFromServer(key);
- listOfKeys.push(key);
- data.it = std::prev(listOfKeys.end());
- } else {
- listOfKeys.erase(data.it);
- listOfKeys.push(key);
- data.it = std::prev(listOfKeys.end());
- }
- return data.dataValue;
- }
- }
- };
- class MyClass
- {
- };
- int myFunc()
- {
- Cache<double> myCache(10, [&] (std::string key) { return DataValue(key); });
- Cache<MyClass> myCache(10);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement