Imagine that you are writing a top-down dynamic algorithm. You already represented your dependencies as recursive functions and now you need to figure out how to decrease the memory usage and calculate things in correct order. On the other hand, you can just apply brute force approach and cache results. How to write caching to be able to reuse it quickly?

Let’s start with code for hashing any parameters. We can use boost implementation:

Now, we can write generic method for caching things:

So we accept first parameter representing the function to call and pack of parameters for actual arguments. Next comes normal cache implementation.

And this is how we call it:

You can see that instead of fib(n-2) I call cached method, pass function for calculating results and all arguments. That’s it.