Skip to content

Instantly share code, notes, and snippets.

@artemkin
Last active August 29, 2015 14:15
Show Gist options
  • Save artemkin/c8143937c532a98c5dc4 to your computer and use it in GitHub Desktop.
Save artemkin/c8143937c532a98c5dc4 to your computer and use it in GitHub Desktop.
// Special case of memoization. Only last value is cached.
#include <iostream>
#include <memory>
template<typename R, typename Arg, typename Comp = std::equal_to<Arg>, typename Fun>
std::function<R(const Arg&)> memoize_last(Fun f)
{
struct Cache
{
R result;
Arg x;
bool init = false;
};
auto cache = std::make_shared<Cache>();
return [=](Arg x) -> R
{
if (cache->init && Comp()(cache->x, x))
{
return cache->result;
}
cache->init = true;
cache->x = x;
cache->result = f(x);
return cache->result;
};
}
int do_complex_calc(int x)
{
std::cout << "COMPLEX CALC: " << x << std::endl;
return x * x;
}
int main()
{
auto calc = memoize_last<int, int>(do_complex_calc);
calc(5);
calc(5);
calc(5);
calc(10);
calc(10);
calc(10);
calc(5);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment