CachedFunction.hpp
Go to the documentation of this file.
1 // Distributed under the MIT License.
2 // See LICENSE.txt for details.
3 
4 /// \file
5 /// Defines class CachedFunction
6 
7 #pragma once
8 
9 #include <type_traits>
10 #include <unordered_map>
11 #include <utility>
12 
13 /// A function wrapper that caches function values.
14 template <typename Function, typename Map>
16  public:
17  using input = typename Map::key_type;
18  using output = typename Map::mapped_type;
19 
20  template <typename... MapArgs>
21  explicit CachedFunction(Function function, MapArgs... map_args) noexcept
22  : function_(std::move(function)),
23  cache_(std::forward<MapArgs>(map_args)...) {}
24 
25  /// Obtain the function result
26  const output& operator()(
27  const input& x) noexcept(noexcept(std::declval<Function>()(x))) {
28  auto it = cache_.find(x);
29  if (it == cache_.end()) {
30  it = cache_.emplace(x, function_(x)).first;
31  }
32  return it->second;
33  }
34 
35  /// Clear the cache entries
36  void clear() noexcept { cache_.clear(); }
37  private:
38  Function function_;
39  Map cache_;
40 };
41 
42 /// Construct a CachedFunction wrapping the given function
43 ///
44 /// \example
45 /// \snippet Test_CachedFunction.cpp make_cached_function_example
46 ///
47 /// \tparam Input function argument type
48 /// \tparam Map class template to use as the map holding the cache
49 /// \param function the function
50 /// \param map_args arguments to pass to the map constructor
51 template <typename Input, template <typename...> class Map = std::unordered_map,
52  typename... MapArgs, typename Function, typename... PassedMapArgs>
53 auto make_cached_function(Function function,
54  PassedMapArgs... map_args) noexcept {
58  MapArgs...>>(
59  std::move(function), std::forward<PassedMapArgs>(map_args)...);
60 }
void clear() noexcept
Clear the cache entries.
Definition: CachedFunction.hpp:36
A function wrapper that caches function values.
Definition: CachedFunction.hpp:15
auto make_cached_function(Function function, PassedMapArgs... map_args) noexcept
Construct a CachedFunction wrapping the given function.
Definition: CachedFunction.hpp:53
const output & operator()(const input &x) noexcept(noexcept(std::declval< Function >()(x)))
Obtain the function result.
Definition: CachedFunction.hpp:26