Last active
May 24, 2016 19:33
-
-
Save safiire/394579f5bf1fd7960b6a to your computer and use it in GitHub Desktop.
Using template meta-programming as a functional language in C++11
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
using namespace std; | |
//// | |
// Pattern match on a list of types, recursively ask for the last one | |
template <typename Head, typename... Tail> | |
struct last { | |
using type = typename last<Tail...>::type; | |
}; | |
//// | |
// Base case typedefs the last type | |
template <typename T> | |
struct last<T> { | |
using type = T; | |
}; | |
//// | |
// Value typed parameter to calculate Fibonacci | |
template <int N> | |
struct fib { | |
static const long long value = N * fib<N - 1>::value; | |
}; | |
//// | |
// Base case returns 1 | |
template <> | |
struct fib<0> { | |
static const long long value = 1; | |
}; | |
//// | |
// This for some reason needs a declaration of variadic | |
// type parameters, whereas the last didn't. | |
template <typename... Types> struct counter; | |
//// | |
// Pattern match on a list of types, count them recursively | |
template <typename Head, typename... Tail> | |
struct counter <Head, Tail...> { | |
static const int value = 1 + counter<Tail...>::value; | |
}; | |
//// | |
// Base case, 0 type parameters | |
template <> | |
struct counter <> { | |
static const int value = 0; | |
}; | |
int main(void){ | |
using t = last<int, double>::type; | |
t pi = 3.14159; // Chose double | |
cout << "Pi is " << pi << endl; | |
cout << "Fib(20) = " << fib<20>::value << endl; | |
cout << "There are " << counter<int, float, double, char>::value << " types" << endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment