28 template <
typename Ret,
typename... Args>
29 auto memoize(std::function<Ret(Args...)> f) -> std::function<Ret(Args...)>
31 auto cache = std::make_shared<std::map<std::tuple<Args...>, Ret>>();
32 return [=](Args... args)
mutable -> Ret
34 std::tuple<Args...> t(args...);
35 if(cache->find(t) == cache->end())
36 (*cache)[t] = f(args...);
41 template<
typename Ret,
typename... Args>
42 auto memoizeLast(std::function<Ret(Args...)> f) -> std::function<Ret(Args...)>
44 std::tuple<typename std::decay<Args>::type...> cache;
46 return [=](Args... args)
mutable -> Ret
48 if(std::tie(args...) == cache)
50 cache = std::make_tuple(args...);
51 return result = f(args...);
55 template<
typename Ret,
typename... Args>
56 auto memoizeLastPtr(std::function<Ret(Args...)> f) -> std::shared_ptr<std::function<Ret(Args...)>>
58 return std::make_shared<std::function<Ret(Args...)>>(memoizeLast(f));
61 template<
typename Ret,
typename... Args>
62 auto dereference(
const std::shared_ptr<std::function<Ret(Args...)>>& f) -> std::function<Ret(Args...)>
64 return [=](Args... args) -> Ret {
return (*f)(args...); };