Documentation of MARTY
A Modern ARtificial Theoretical phYsicist
cache.h
1 #pragma once
2 
3 #include <functional>
4 #include <csl.h>
5 
6 namespace mty {
7 
8 template<class T, class U>
9 class Cache {
10 
11 public:
12 
13  using CachedData = std::pair<T, U>;
14  using Comparator = std::function<bool(T const&, T const&)>;
15  using Releaser = std::function<U(U const&)>;
16  IMPLEMENTS_STD_VECTOR(CachedData, cached)
17 
18  explicit
19  Cache(
20  Comparator &&t_comparator = [](T const &a, T const &b) { return a == b; },
21  Releaser &&t_releaser = [](U const &res) { return res; }
22  )
23  :comparator(std::forward<Comparator>(t_comparator)),
24  releaser(std::forward<Releaser>(t_releaser))
25  {
26 
27  }
28 
29  template<class Calculator>
30  U calculate(T const &input, Calculator &&calc)
31  {
32  if (auto pos = find(input) ; pos != end()) {
33  return releaser(pos->second);
34  }
35  return releaser(add(input, calc(input)));
36  }
37 
38  auto find(T const &key) {
39  return std::find_if(cached.begin(), cached.end(),
40  [&](CachedData const &data) {
41  return comparator(data.first, key);
42  });
43  }
44 
45  auto find(T const &key) const {
46  return std::find_if(cached.begin(), cached.end(),
47  [&](CachedData const &data) {
48  return comparator(data.first, key);
49  });
50  }
51 
52 private:
53 
54  U const &add(T const &key, U const &value) {
55  if (auto pos = find(key) ; pos == end()) {
56  cached.push_back({key, releaser(value)});
57  return cached.back().second;
58  }
59  else {
60  return pos->second;
61  }
62  }
63 
64 private:
65 
66  std::vector<CachedData> cached;
67  Comparator comparator;
68  Releaser releaser;
69 };
70 
71 } // namespace mty
Namespace of MARTY.
Definition: 2HDM.h:31
Definition: cache.h:9