When you write
...it seems like the map isn't unique to each instance of the memoized functions. Is this expected?
you seem to forget that the instance wrt to static
variables is based on the types, not on the value of the parameters. The type std::function<outType(inType)>
is the same in both cases. Obviously, when there is only one instance you also have only one static map
.
A partial solution could be this:
template<typename inType, typename outType>
std::function<outType(inType) > memoize(std::function<outType(inType) > foo) {
static int i = 0;
++i;
return [foo](inType n) {
static std::map<int, std::map<inType, outType>> memo;
auto& m = memo[i];
outType ret;
if (m.count(n) > 0) {
cout << "Cache Hit" << endl;
ret = m[n];
return ret;
}
ret = foo(n);
m[n] = ret;
return ret;
};
}
But note that now each call will generate its own independent map
. If you do:
auto f1 = memoize(factorial_r);
auto f2 = memoize(factorial_r);
then f1
and f2
will not share the same map
. This also means that if you do this very often, you might end up using a lot of memory.