diff options
author | Dan Goodliffe <dan@randomdan.homeip.net> | 2021-01-23 14:01:01 +0000 |
---|---|---|
committer | Dan Goodliffe <dan@randomdan.homeip.net> | 2021-01-23 14:10:15 +0000 |
commit | 6c417830105d27d151284546c6482f0f6eccef26 (patch) | |
tree | c93735528822e6acdd87e1188e55c14da8d7f785 /lib | |
parent | Add basic work and worker thread pool (diff) | |
download | ilt-6c417830105d27d151284546c6482f0f6eccef26.tar.bz2 ilt-6c417830105d27d151284546c6482f0f6eccef26.tar.xz ilt-6c417830105d27d151284546c6482f0f6eccef26.zip |
Add a basic cache template
Diffstat (limited to 'lib')
-rw-r--r-- | lib/cache.h | 29 |
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 |