First commit
[cpp_sandbox.git] / Sandbox / FunctionsAsTemplate.cpp
1 #include "FunctionsAsTemplate.h"
2
3 #include <iostream>
4 #include <map>
5 using namespace std;
6
7 #include "Types.h"
8
9 namespace FunctionsAsTemplate
10 {
11 template <i64(*f)(i64)>
12 i64 memoize(i64 x)
13 {
14 static std::map<i64, i64> cache;
15 auto i = cache.find(x);
16 if (i != cache.end())
17 return i->second;
18 else
19 return cache[x] = f(x);
20 }
21
22 i64 fib(i64 n) {
23 if (n < 2)
24 return n;
25 else
26 return memoize<fib>(n - 1) + memoize<fib>(n - 2);
27 }
28 }
29
30 void FunctionsAsTemplate::tests()
31 {
32 i64 n = 80;
33 cout << "fib(" << n << ") = " << fib(n) << endl;
34 }