summaryrefslogtreecommitdiff
path: root/lib/cache.h
diff options
context:
space:
mode:
Diffstat (limited to 'lib/cache.h')
-rw-r--r--lib/cache.h29
1 files changed, 29 insertions, 0 deletions
diff --git a/lib/cache.h b/lib/cache.h
new file mode 100644
index 0000000..48b9c55
--- /dev/null
+++ b/lib/cache.h
@@ -0,0 +1,29 @@
+#ifndef CACHE_H
+#define CACHE_H
+
+#include <map>
+#include <memory>
+
+template<typename Obj> class Cache {
+public:
+ using Ptr = std::shared_ptr<Obj>;
+ [[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