Skip to content

Instantly share code, notes, and snippets.

@artsobolev
Last active December 15, 2015 13:59
Show Gist options
  • Save artsobolev/5270779 to your computer and use it in GitHub Desktop.
Save artsobolev/5270779 to your computer and use it in GitHub Desktop.
#include <iostream>
#include "Memoizator.hpp"
int f(int a) {
std::cout << __func__ << "(" << a << ")\n";
return a*a;
}
int g(int a, int b) {
std::cout << __func__ << "(" << a << ", " << b << ")\n";
return a*b;
}
int main() {
auto memo_f = memoize(f);
auto memo_g = memoize(g);
int v;
for (int i = 0; i < 100; ++i) {
v += memo_f(i % 17) * memo_g(i % 91, i % 37);
}
std::cout << v << std::endl;
return 0;
}
#ifndef MEMOIZATOR
#define MEMOIZATOR
#include <tuple>
#include <map>
template<class R, class... Args>
class Memoizator {
typedef std::tuple<Args...> tuple;
public:
typedef R (*function)(Args...);
Memoizator(function f) : f(f) {}
R operator()(Args... args) {
tuple argset(args...);
auto it = map.find(argset);
if (it != map.end()) {
return it->second;
}
return map[argset] = f(args...);
}
private:
function f;
std::map<tuple, R> map;
};
template<class R, class... Args>
Memoizator<R, Args...> memoize(R (*f)(Args...)) {
return Memoizator<R, Args...>(f);
}
#endif // MEMOIZATOR
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment