I had recently read an article which explained how functional programming style can be adopted by using template metaprogramming. The ” hello world ” equivalent for TMP is the factorial computation – which can be described as follows

fc 0 = 0
fc 1 = 1
fc parm = parm * fc (parm-1)

and the c++ equivalent can be expressed as

#include <iostream>
template <int parm>
struct fact {
static const int val = parm * fact< parm - 1 >::val;
};
template <>
struct fact<1> {
static const int val = 1;
};
template <>
struct fact<0> {
static const int val = 0;
};
int main() {
std::cout << fact<5>::val;
return 0;
}

Right. So this was already available everywhere. Thus I decided to write a similar kind of program in haskell and then implement it using TMP in C++. The problem I took up was very simple – to find the sum of numbers in a list.

In haskell, this program is trivial –

sumList (x:xs) = x + sumList xs
sumList _ = 0

That was easy. Now looking forward to TMP – we use variadic templates to perform the same thing

#include <iostream>
template<int... Values> struct List;
template<int x1, int x2, int... Values>
struct List< x1, x2, Values... > {
static int const value = x1 + x2 + List< Values... >::value;
};
template<int x1>
struct List< x1 > {
static int const value = x1;
};
template<>
struct List<> {
static int const value = 0;
};
int main() {
std::cout << List<1,2,3,4,5>::value;
return 0;
}

That’s it for now. I’ll try and solve something else using haskell and then try and translate it in terms of TMP. Till then.

### Like this:

Like Loading...

*Related*