Skip to content

Instantly share code, notes, and snippets.

@safiire
Last active May 24, 2016 19:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save safiire/394579f5bf1fd7960b6a to your computer and use it in GitHub Desktop.
Save safiire/394579f5bf1fd7960b6a to your computer and use it in GitHub Desktop.
Using template meta-programming as a functional language in C++11
#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