shared_cache.h 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. //
  2. // shared_cache.h
  3. // serializer
  4. //
  5. // Created by Sam Jaffe on 3/15/23.
  6. //
  7. #pragma once
  8. #include <memory>
  9. #include <string>
  10. namespace serializer {
  11. class SharedCache {
  12. public:
  13. using Key = std::string;
  14. template <typename T> using Record = std::shared_ptr<T const>;
  15. protected:
  16. struct Impl {
  17. virtual ~Impl() = default;
  18. };
  19. private:
  20. std::unique_ptr<Impl> p_impl = std::make_unique<Impl>();
  21. public:
  22. SharedCache() = default;
  23. /**
  24. * @brief Store an object within this cache, returning a pointer to the
  25. * cached object. In order to be nullptr-safe, the unspecialized version
  26. * of this function returns a shared_ptr containing a copy of value.
  27. * Specialized versions exist in shared_cache.cxx, which actually perform
  28. * caching.
  29. * @param key The name of the value, for looking up later
  30. * @param value The value to store within this cache
  31. * @return A shared_ptr containing the cached value
  32. */
  33. template <typename T> Record<T> store(Key const & key, T const & value) {
  34. return std::make_shared<T>(value);
  35. }
  36. /**
  37. * @brief Fetch an object that was cached within this object.
  38. * @param key The name of the cached object, as called in store()
  39. * @return A shared_ptr containing the requested object, or null if it isn't
  40. * found in this cache.
  41. * @throws std::domain_error if no specialization is defined
  42. */
  43. template <typename T> Record<T> fetch(Key const & key) const {
  44. throw std::domain_error(typeid(T).name());
  45. }
  46. protected:
  47. template <typename T>
  48. SharedCache(std::unique_ptr<T> ptr) : p_impl(std::move(ptr)) {}
  49. };
  50. }