Skip to content

Instantly share code, notes, and snippets.

@apples
Created May 22, 2016 03:47
Show Gist options
  • Save apples/09f8e0f435fe670d2cc7e60be33c1d92 to your computer and use it in GitHub Desktop.
Save apples/09f8e0f435fe670d2cc7e60be33c1d92 to your computer and use it in GitHub Desktop.
#ifndef BRAEBURN_RESOURCECACHE_HPP
#define BRAEBURN_RESOURCECACHE_HPP
#include <memory>
#include <string>
#include <unordered_map>
#include <typeindex>
namespace braeburn {
class ResourceCache {
public:
template <typename T>
std::shared_ptr<T> get(const std::string& name) const {
auto& factory = cache_map.at(typeid(T));
auto& wptr = factory.cache[name];
auto ptr = wptr.lock();
if (!ptr) {
ptr = factory.create(name);
wptr = ptr;
}
return std::static_pointer_cast<T>(ptr);
}
template <typename T>
void enable(std::function<std::shared_ptr<void>(const std::string&)> create) {
cache_map.emplace(typeid(T),Factory{{},std::move(create)});
}
private:
struct Factory {
mutable std::unordered_map<std::string,std::weak_ptr<void>> cache;
std::function<std::shared_ptr<void>(const std::string&)> create;
};
std::unordered_map<std::type_index, Factory> cache_map;
};
} // namespace braeburn
#endif // BRAEBURN_RESOURCECACHE_HPP
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment