Template Meta Programming (TMP) was accidentally discovered and was not an intended feature of the language. It has many applications such as generating complex code at compile time and writing compile time checks to see if a type satisfies a given condition. It is a Turing complete language in and of itself. It is purely functional as well. Like all functional languages it can manipulate lists. Lists can be represented as a type which stores 2 other types one of which can be another pair; that can continue until a terminating value is reached. Functions can be represented as template classes.
I present to you a small framework for creating template meta lists and a couple of meta functions which can be applied to lists using a left fold. Your challenge is to write a class (or meta function) that performs a left fold. 2 test cases are in used in main.
#include <iostream>
//specil type for ending lists
struct meta_null {};
//type to hold value pairs; these pairs can form lists
template<class Head, class Tail>
struct meta_pair {
typedef Head head;
typedef Tail tail;
};
//a simple type that holds a value
template<int x>
struct meta_int {
static const int value = x;
};
template<class I1, class I2>
struct add {
typedef meta_int<I1::value + I2::value> value;
};
template<class I1, class I2>
struct mul {
typedef meta_int<I1::value * I2::value> value;
};
int main() {
typedef meta_pair<meta_int<1>,
meta_pair<meta_int<2>,
meta_pair<meta_int<3>,
meta_pair<meta_int<4>,
meta_pair<meta_int<5>, meta_null> > > > > test_list;
//find the sum of values in the list
std::cout<<fold_l<add, meta_int<0>, test_list>::value::value;
std::cout<<'\n';
std::cout<<fold_l<mul, meta_int<1>, test_list>::value::value;
return 0;
}
For added challenge write a...
- right fold function
- a map function
- a sum function (sums a list)
- a product function (product of list).
- something i haven't thought of

Also, if you have any other TMP goodies, It would be nice if you could posts those too
hint 1:
hint 2:
hint 3:
If your struggling with TMP or simply want to know more about it, i recommend reading this article which compares TMP to Haskell. The same author also has this article on TMP
This post has been edited by ishkabible: 06 December 2011 - 03:59 PM

New Topic/Question
Reply






MultiQuote




|