I know how to do memoization in Python easily but I need a faster way to compute them, so I am using C++. However, I have no clue how to memoize. I understand that it\'s abo
Just for fun, here's a little generic memoizer I wrote some time ago. It requires variadic templates, naturally:
template class Container, typename...> struct Memo;
template class Container>
struct Memo>
{
Memo(std::function f) : func(f) { }
R operator()(Args && ...args)
{
const auto arg = std::make_tuple(args...);
typename CacheContainer::const_iterator it = cache.find(arg);
if (it == cache.cend())
{
it = cache.insert(typename CacheContainer::value_type(arg, func(std::forward(args)...))).first;
std::cout << "New call, memoizing..." << std::endl;
}
else
{
std::cout << "Found it in the cache!" << std::endl;
}
return it->second;
}
private:
typedef Container, R> CacheContainer;
std::function func;
CacheContainer cache;
};
template
Memo> OMapMemoize(R(&f)(Args...))
{
return Memo>(f);
}
template
Memo> UMapMemoize(R(&f)(Args...))
{
return Memo>(f);
}
I'm not entirely sure if I got the rvalue-forwardiness right, as it's a long time ago that I wrote this. Anyway, here's a test case:
int foo(double, char) { return 5; }
int main()
{
auto f = OMapMemoize(foo);
auto g = UMapMemoize(foo);
int a, b;
a = f(1.0, 'a');
a = f(1.0, 'a');
a = f(1.0, 'a');
a = f(1.0, 'a');
b = g(1.0, 'a');
b = g(1.0, 'a');
b = g(1.0, 'a');
b = g(1.0, 'a');
return a;
}