Sumant Tambe (17) [Avatar] Offline
#1
I thought the memoize_helper template is too complicated and might detract the readers from considering/using memoization. There're alternative simpler implementations of the idea. What do you think of http://cpptruths.blogspot.com/2012/01/general-purpose-automatic-memoization.html
Ivan Cukic (99) [Avatar] Offline
#2
Hi Sumant,

Thanks for the link. I'll be putting it in the 'futher reading' section as the alternative implementation.

While it does make some things simpler, I'm not very fond of using `std::function` and static maps for this.

The reason why I went for the solution presented in the book is that it uses only the things I covered in the book before - function objects, thread-safe const call operator, etc.

Cheers,
Ivan

p.s. Cool idea adding the Cache::RECLAIM. smilie
Sumant Tambe (17) [Avatar] Offline
#3
At the risk of annoying you, I want to mention that the approach can be simplified that does not use std::function or static maps. The new approach still depends on static state that is well encapsulated. On the plus side, the implementation fits in 20 lines code. Here's live code: https://wandbox.org/permlink/3Qu57z15xMBRVijR

Thoughts?
Ivan Cukic (99) [Avatar] Offline
#4
> At the risk of annoying you

No risk of that - I love useful contributions. If KDE users were as helpful when reporting bugs, my life would be much better smilie

> I want to mention that the approach can be
> simplified that does not use std::function or static maps.

I like this one much better than the previous solution.

As far as the implementation goes, I would make the call operator `const`. Memoization is an implementation detail, and the absence of `const` hints that something is being mutated while it should not - fib is a pure function. This would also need the recursive mutex to guard the changes.

The reason I am not fond of the `static` part is that it reuqires manual memory management. Namely, the user of the function needs to remember to call the `STATIC_MEMOIZER_CLEAR`. The non-static version clears up the cache as soon as the function object gets destroyed.

Now, I'm not saying that static cache does not have its advantages, and that I would not use it in my own code to have a greater control over the cache, but I'm trying to advocate safety before control.

Can you add this solution to your blog post for completeness? I think it is quite beneficial as the "further reading".