| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758 |
- //
- // shared_cache.h
- // serializer
- //
- // Created by Sam Jaffe on 3/15/23.
- //
- #pragma once
- #include <memory>
- #include <string>
- namespace serializer {
- class SharedCache {
- public:
- using Key = std::string;
- template <typename T> using Record = std::shared_ptr<T const>;
- protected:
- struct Impl {
- virtual ~Impl() = default;
- };
- private:
- std::unique_ptr<Impl> p_impl = std::make_unique<Impl>();
- public:
- SharedCache() = default;
- /**
- * @brief Store an object within this cache, returning a pointer to the
- * cached object. In order to be nullptr-safe, the unspecialized version
- * of this function returns a shared_ptr containing a copy of value.
- * Specialized versions exist in shared_cache.cxx, which actually perform
- * caching.
- * @param key The name of the value, for looking up later
- * @param value The value to store within this cache
- * @return A shared_ptr containing the cached value
- */
- template <typename T> Record<T> store(Key const & key, T const & value) {
- return std::make_shared<T>(value);
- }
- /**
- * @brief Fetch an object that was cached within this object.
- * @param key The name of the cached object, as called in store()
- * @return A shared_ptr containing the requested object, or null if it isn't
- * found in this cache.
- * @throws std::domain_error if no specialization is defined
- */
- template <typename T> Record<T> fetch(Key const & key) const {
- throw std::domain_error(typeid(T).name());
- }
- protected:
- template <typename T>
- SharedCache(std::unique_ptr<T> ptr) : p_impl(std::move(ptr)) {}
- };
- }
|