boat
C++23 geospatial library
Loading...
Searching...
No Matches
cache.hpp
Go to the documentation of this file.
1// Andrew Naplavkov
2
3#ifndef BOAT_GUI_CACHES_CACHE_HPP
4#define BOAT_GUI_CACHES_CACHE_HPP
5
6#include <atomic>
7#include <boat/detail/any_hashable.hpp>
8#include <functional>
9#include <type_traits>
10
12
13struct cache {
14 virtual ~cache() = default;
15
17 virtual std::any get(any_hashable const&) = 0;
18
19 virtual void put(any_hashable, std::any) = 0;
20};
21
22template <class F, class... Args>
23auto get_or_invoke(cache* ptr, any_hashable const& key, F&& f, Args&&... args)
24{
25 if (auto any = ptr ? ptr->get(key) : std::any{}; any.has_value())
26 return std::any_cast<std::decay_t<std::invoke_result_t<F, Args...>>>(
27 std::move(any));
28 auto ret = std::invoke(std::forward<F>(f), std::forward<Args>(args)...);
29 if (ptr)
30 ptr->put(key, ret);
31 return ret;
32}
33
34inline size_t next_key()
35{
36 static constinit std::atomic_size_t seq_;
37 return ++seq_;
38}
39
40} // namespace boat::gui::caches
41
42#endif // BOAT_GUI_CACHES_CACHE_HPP
Definition cache.hpp:11
auto get_or_invoke(cache *ptr, any_hashable const &key, F &&f, Args &&... args)
Definition cache.hpp:23
size_t next_key()
Definition cache.hpp:34
Definition cache.hpp:13
virtual std::any get(any_hashable const &)=0
Returns an empty std::any on a miss.
virtual ~cache()=default
virtual void put(any_hashable, std::any)=0