Caching the value using the memoization technique

We now have successfully delayed the execution of the function by consuming the Delay class. However, since the function of the Delay class instance will be run each time the Fetch() method is invoked, an unexpected result might occur if the function is not pure or has side effects. Let's refactor our previous delaying.cpp code by modifying the multiply function. This function now becomes a non-pure function since it depends on an outside variable. The code should look like this:

    /* delaying_non_pure.cpp */    #include <iostream>    #include <functional>    using namespace std;    template<class T> class Delay    {      private:        function<T()> m_func;      public:        Delay(function<T()> func) : m_func(func)        {        }  T Fetch() ...

Get Learning C++ Functional Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.