I found an article that contains this code:
template <typename ReturnType, typename... Args>
std::function<ReturnType (Args...)>
memoize(std::function<ReturnType (Args...)> func)
{
std::map<std::tuple<Args...>, ReturnType> cache;
return ([=](Args... args) mutable {
std::tuple<Args...> t(args...);
if (cache.find(t) == cache.end())
cache[t] = func(args...);
return cache[t];
});
}
Can you explain this please? I can’t understand many things here, but the weirdest thing is that cache is local and not static, but maybe I’m wrong and…
This is simple C++1x implementation of memoization.
The
memoizefunction returns a closure. The return value is a function that has state other than what is passed through the arguments (in this case, thecachevariable).The
[=]bit in the anonymous function indicates that the returned function should take a copy of all local variables. Thecachevariable is not static because it is meant to be shared across invocations of the returned function.Thus, each call to
memoizewill return a different function with it’s owncache. Subsequent calls to a specific closure returned bymemoizewill insert/fetch values from that closure’scache.You can think of this as a somewhat equivalent to the more old-school OOP version: