OGLplus  (0.59.0) a C++ wrapper for rendering APIs

memoized.hpp
Go to the documentation of this file.
1 
9 #ifndef EAGINE_MEMOIZED_HPP
10 #define EAGINE_MEMOIZED_HPP
11 
12 #include "callable_ref.hpp"
13 #include <map>
14 #include <tuple>
15 
16 namespace eagine {
17 
18 template <typename F>
19 class memoized;
20 
21 template <typename R, typename... P>
22 class memoized<R(P...)> {
23 private:
24  using T = std::tuple<P...>;
25  using E = std::pair<T, R>;
26  std::map<T, R> _memo;
27  callable_ref<R(P..., memoized&)> _func;
28 
29 public:
30  template <
31  typename Func,
32  typename = std::enable_if_t<!std::is_same_v<std::decay_t<Func>, memoized>>>
33  memoized(Func&& func)
34  : _func(std::forward<Func>(func)) {}
35 
36  template <typename F>
37  auto operator()(P... p, const F& f) -> R {
38  T t(p...);
39  auto i = _memo.find(t);
40  if(i == _memo.end()) {
41  i = _memo.insert(E(t, f(p..., *this))).first;
42  }
43  return i->second;
44  }
45 
46  auto operator()(P... p) -> R {
47  return _func(p..., *this);
48  }
49 
50  void reset(P... p) {
51  _memo.erase(T(p...));
52  }
53 
54  void clear() {
55  _memo.clear();
56  }
57 };
58 
59 } // namespace eagine
60 
61 #endif // EAGINE_MEMOIZED_HPP
Common code is placed in this namespace.
Definition: eagine.hpp:21
basic_callable_ref< Sig, is_noexcept_function_v< Sig > > callable_ref
Alias for callable object references.
Definition: callable_ref.hpp:191

Copyright © 2015-2021 Matúš Chochlík.
<chochlik -at -gmail.com>
Documentation generated on Tue Apr 13 2021 by Doxygen (version 1.8.17).