Template metaprogramming V: Face to face
By now we have learned the basics for a nice template metaprogramming toolkit:
|
![]() |
Unfortunately that’s all you need for a Turing complete language, meaning now we have the power, bwahahaha! Mph, I’m sorry, back on topic, it means we can now create a fully functional and useful template metaprogramming device… for approximating e, nonetheless. Oh, you think that’s not useful? Well though luck, that’s all you get for now:
-
template struct Frak {
-
static const long Num = N;
-
static const long Den = D;
-
};
-
-
template struct MultEscalar {
-
typedef Frak< N*X::Num, N*X::Den > result;
-
};
-
-
template struct IgualBase {
-
typedef typename MultEscalar< X1, Y1::Den >::result X;
-
typedef typename MultEscalar< Y1, X1::Den >::result Y;
-
};
-
-
template struct MCD {
-
static const long result = MCD::result;
-
};
-
template struct MCD {
-
static const long result = X;
-
};
-
-
template struct Simpl {
-
static const long mcd = MCD::result;
-
typedef Frak< F::Num / mcd, F::Den / mcd > result;
-
};
-
-
template struct Suma {
-
typedef IgualBase B;
-
static const long Num = B::X::Num + B::Y::Num;
-
static const long Den = B::Y::Den; // == B::X::Den
-
typedef typename Simpl< Frak >::result result;
-
};
-
-
template struct Fact {
-
static const long result = N * Fact::result;
-
};
-
template <> struct Fact<0> {
-
static const long result = 1;
-
};
-
-
template struct E {
-
// e = S(1/n!) = 1/0! + 1/1! + 1/2! + …
-
static const long Den = Fact::result;
-
typedef Frak< 1, Den > term;
-
typedef typename E::result next_term;
-
typedef typename Suma< term, next_term >::result result;
-
};
-
template <> struct E<0> {
-
typedef Frak<1, 1> result;
-
};
-
-
#include
-
int main() {
-
typedef E<8>::result X;
-
return 0;
-
}
Looking nice, isn’t it? You should have all what’s needed to understand what’s going on there. Even more, almost everything has been explained in previous articles, with the exception of EqBase. But that’s left as an exersice for the reader because the writer is too lazy.
If you think any part of the code requires clarification ask in the comments. Next, a long overdue topic: lists using template metaprogramming. Guaranteed to blow your mind into little pieces!

Posted by: nico on
May 12th, 2010 |
Filed under: 



Add A Comment