summaryrefslogtreecommitdiff
path: root/lib/cache.h
blob: 2a6e3e5d2e91b6413249205c4053397ea3c77a5d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#ifndef CACHE_H
#define CACHE_H

#include <map>
#include <memory>

template<typename Obj> class Cache {
public:
	using Ptr = std::shared_ptr<Obj>;

	virtual ~Cache() = default;

	[[nodiscard]] Ptr
	get(const std::string & key)
	{
		if (auto e = cached.find(key); e != cached.end()) {
			return e->second;
		}
		return cached.emplace(key, construct(key)).first->second;
	}

	[[nodiscard]] virtual Ptr
	construct(const std::string & key) const
	{
		return std::make_shared<Obj>(key);
	}

private:
	std::map<std::string, Ptr> cached;
};

#endif