Following on from Stoned_Coder's metaprogramming example...here's something I was working on for a contest a while ago...it was to add 2 fractions at compile time and rationalize them down....bit of a pig to read!
Code:
#include <iostream>
#include <cassert>
//Main struct interface
template <int n1, int d1, int n2, int d2>
struct add_fraction
{
static const int numerator;
static const int denominator;
};
//Specialisation 1: Subvert functionality
template <int n1, int d1>
struct add_fraction<n1,d1,0,0>
{
static const int denominator = add_fraction<d1,n1%d1,0,0>::denominator;
};
//Specialisation 2: Assign value
template <int n1>
struct add_fraction<n1,0,0,0>
{
static const int denominator = n1;
};
//The Numerator
template <int n1, int d1, int n2, int d2>
const int add_fraction<n1,d1,n2,d2>::numerator =
((((d2*d1)/d1)*n1)+(((d2*d1)/d2)*n2)) /
add_fraction<((((d2*d1)/d1)*n1)+(((d2*d1)/d2)*n2)),
((d2*d1)%((((d2*d1)/d1)*n1)+(((d2*d1)/d2)*n2))),0,0>::denominator;
//The Denominator
template <int n1, int d1, int n2, int d2>
const int add_fraction<n1,d1,n2,d2>::denominator = (d1*d2)/
add_fraction<((((d2*d1)/d1)*n1)+(((d2*d1)/d2)*n2)),
((d2*d1)%((((d2*d1)/d1)*n1)+(((d2*d1)/d2)*n2))),0,0>::denominator;
int main() {
typedef add_fraction<2,3,1,12> three_fourths;
assert(three_fourths::numerator==3);
assert(three_fourths::denominator==4);
std::cout << three_fourths::numerator;
std::cout << std::endl << "--" << std::endl;
std::cout << three_fourths::denominator;
}