First commit
[cpp_sandbox.git] / Sandbox / TemplateMetaProgramming.cpp
1 #include "TemplateMetaProgramming.h"
2
3 #include <iostream>
4 #include <utility>
5 #include <array>
6 using namespace std;
7
8 #include "Types.h"
9
10 // See chapter 28 of "The C++ programming language".
11
12 namespace TemplateMetaProgramming
13 {
14 template<i64 I>
15 struct Fib
16 {
17 static const i64 val = Fib<I - 1>::val + Fib<I - 2>::val;
18 };
19
20 template<>
21 struct Fib<0>
22 {
23 static const i64 val = 0;
24 };
25
26 template<>
27 struct Fib<1>
28 {
29 static const i64 val = 1;
30 };
31
32 /////
33
34 template<i64 ... I>
35 i64 fib_impl(integer_sequence<i64, I...>, const i64 i)
36 {
37 constexpr array<i64, sizeof...(I)> a = { Fib<I>::val... };
38 return a[i];
39 }
40
41 i64 fib(const i64 i)
42 {
43 // Generate all fibonacci sequence from 0 to 80.
44 return fib_impl(make_integer_sequence<i64, 81>(), i);
45 }
46 }
47
48 void TemplateMetaProgramming::tests()
49 {
50 constexpr i64 n = 80;
51 cout << "Compile time: fib(" << n << ") = " << Fib<n>::val << endl;
52
53 const i64 m = 80;
54 cout << "Run time: fib(" << m << ") = " << fib(m) << endl;
55 }