Memoization via template This is kind of follow up of this question on stack overflow...

I wrote the following to utilize memoization for functions that take a single parameter and return a value:

#include &lt;iostream&gt;
#include &lt;map&gt;
using namespace std;

template &lt;class T, class R, R (*Func)(T)&gt;
R memoized(T in) {
    static std::map&lt;T,R&gt; memo;
    typename std::map&lt;T,R&gt;::iterator found = memo.find(in);
    if (found != memo.end()) { return found-&gt;second; }  
    std::cout &lt;&lt; "not found" &lt;&lt; std::endl; // only for demo
    R res = Func(in);
    memo[in] = res;
    return res;
}

double test(double x){return x*x;}
double test2(double x){return x;}

int main() {
    std::cout &lt;&lt; memoized&lt;double,double,test&gt;(1) &lt;&lt; std::endl;
    std::cout &lt;&lt; memoized&lt;double,double,test&gt;(1) &lt;&lt; std::endl;
    std::cout &lt;&lt; memoized&lt;double,double,test&gt;(1) &lt;&lt; std::endl;
    std::cout &lt;&lt; std::endl;
    std::cout &lt;&lt; memoized&lt;double,double,test2&gt;(1) &lt;&lt; std::endl;
    std::cout &lt;&lt; memoized&lt;double,double,test2&gt;(1) &lt;&lt; std::endl;
    std::cout &lt;&lt; memoized&lt;double,double,test2&gt;(1) &lt;&lt; std::endl;

    return 0;
}


output:

not found
1
1
1

not found
1
1
1


It is a rather strong restriction that it works only for functions taking a single parameter, but thats ok for now. Is there anything else wrong with this approach?

PS: on purpose this is using only pre C++11
I would change memoized to work with a functor type and use a traits approach to deduce the return type and the argument type.

template &lt;typename Functor&gt;
typename Functor::R memoized(typename Functor::T in) {
   using T = typename Functor::T;
   using R = typename Functor::R;

   static std::map&lt;T,R&gt; memo;
   typename std::map&lt;T,R&gt;::iterator found = memo.find(in);
   if (found != memo.end()) { return found-&gt;second; }  
   std::cout &lt;&lt; "not found" &lt;&lt; std::endl; // only for demo
   R res = Functor()(in);
   memo[in] = res;
   return res;
}

struct Test1
{
   using T = double;
   using R = double;
   R operator()(T x) { return x*x; }
};

struct Test2
{
   using T = double;
   using R = double;
   R operator()(T x) { return x; }
};


My rationale for using a functor is that it simplifies user code.

int main() {
    std::cout &lt;&lt; memoized&lt;Test1&gt;(1) &lt;&lt; std::endl;
    std::cout &lt;&lt; memoized&lt;Test1&gt;(1) &lt;&lt; std::endl;
    std::cout &lt;&lt; memoized&lt;Test1&gt;(1) &lt;&lt; std::endl;
    std::cout &lt;&lt; std::endl;
    std::cout &lt;&lt; memoized&lt;Test2&gt;(1) &lt;&lt; std::endl;
    std::cout &lt;&lt; memoized&lt;Test2&gt;(1) &lt;&lt; std::endl;
    std::cout &lt;&lt; memoized&lt;Test2&gt;(1) &lt;&lt; std::endl;

    return 0;
}