Empirical
Cache.h
Go to the documentation of this file.
1 
11 #ifndef EMP_CACHE_H
12 #define EMP_CACHE_H
13 
14 #include <functional>
15 #include <unordered_map>
16 
17 namespace emp {
18 
19  template <class KEY, // Cache::key_type
20  class T, // Cache::mapped_type
21  class HASH = std::hash<KEY>, // Cache::hasher
22  class PRED = std::equal_to<KEY>, // Cache::key_equal
23  class ALLOC = std::allocator< std::pair<const KEY,T> > // Cache::allocator_type
24  >
25  class Cache {
26  private:
27  std::unordered_map<KEY, T, HASH, PRED, ALLOC> cache_map;
28 
29  public:
30  Cache() : cache_map() { }
31  Cache(const Cache &) = default;
32  Cache(Cache &&) = default;
33  Cache & operator=(const Cache &) = default;
34  Cache & operator=(Cache &&) = default;
35 
36  using key_type = KEY;
37  using mapped_type = T;
38  using hasher = HASH;
39  using key_equal = PRED;
40  using allocator_type = ALLOC;
41 
43  size_t size() const { return cache_map.size(); }
44 
46  bool Has(const KEY & k) const { return cache_map.find(k) != cache_map.end(); }
47 
49  void Clear() { cache_map.clear(); }
50 
52  void Erase(const KEY & k) { cache_map.erase(k); }
53 
55  T Get(KEY k, const std::function<T(KEY k)> & calc_fun) {
56  auto cache_it = cache_map.find(k);
57  if (cache_it != cache_map.end()) return cache_it->second;
58  return cache_map.emplace(k, calc_fun(k)).first->second;
59  }
60 
62  const T & GetRef(const KEY & k, const std::function<T(const KEY & k)> & calc_fun) {
63  auto cache_it = cache_map.find(k);
64  if (cache_it != cache_map.end()) return cache_it->second;
65  return cache_map.emplace(k, calc_fun(k)).first->second;
66  }
67 
68  };
69 
70 }
71 
72 #endif
void Erase(const KEY &k)
Erase a specific entry from cache.
Definition: Cache.h:52
HASH hasher
Hash method to use.
Definition: Cache.h:38
ALLOC allocator_type
Function to allocate new space.
Definition: Cache.h:40
Cache & operator=(const Cache &)=default
T Get(KEY k, const std::function< T(KEY k)> &calc_fun)
Lookup a specific key; provide a function to use if value is not in cahce.
Definition: Cache.h:55
void Clear()
Erase contents of cache.
Definition: Cache.h:49
Definition: Cache.h:25
T mapped_type
Contents of the value we look up.
Definition: Cache.h:37
size_t size() const
How many entries are stored in the cache?
Definition: Cache.h:43
PRED key_equal
Function to test if two values are identical.
Definition: Cache.h:39
bool Has(const KEY &k) const
Determine if a specific key is already in the cache.
Definition: Cache.h:46
If we are in emscripten, make sure to include the header.
Definition: array.h:37
KEY key_type
Type we are using to look up values.
Definition: Cache.h:36
const T & GetRef(const KEY &k, const std::function< T(const KEY &k)> &calc_fun)
A version of Get that allows calls with const references instead of pass-by-value.
Definition: Cache.h:62
Cache()
Definition: Cache.h:30