From 6c417830105d27d151284546c6482f0f6eccef26 Mon Sep 17 00:00:00 2001 From: Dan Goodliffe Date: Sat, 23 Jan 2021 14:01:01 +0000 Subject: Add a basic cache template --- lib/cache.h | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 lib/cache.h 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 +#include + +template class Cache { +public: + using Ptr = std::shared_ptr; + [[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(key); + } + +private: + std::map cached; +}; + +#endif -- cgit v1.2.3