shared_cache.h 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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. public:
  16. SharedCache();
  17. ~SharedCache();
  18. /**
  19. * @brief Store an object within this cache, returning a pointer to the
  20. * cached object. In order to be nullptr-safe, the unspecialized version
  21. * of this function returns a shared_ptr containing a copy of value.
  22. * Specialized versions exist in shared_cache.cxx, which actually perform
  23. * caching.
  24. * @param key The name of the value, for looking up later
  25. * @param value The value to store within this cache
  26. * @return A shared_ptr containing the cached value
  27. */
  28. template <typename T> Record<T> store(Key const & key, T const & value) {
  29. return std::make_shared<T>(value);
  30. }
  31. /**
  32. * @brief Fetch an object that was cached within this object.
  33. * @param key The name of the cached object, as called in store()
  34. * @return A shared_ptr containing the requested object, or null if it isn't
  35. * found in this cache.
  36. * @throws std::domain_error if no specialization is defined
  37. */
  38. template <typename T> Record<T> fetch(Key const & key) const {
  39. throw std::domain_error(typeid(T).name());
  40. }
  41. private:
  42. struct Impl;
  43. std::unique_ptr<Impl> p_impl;
  44. };
  45. }