C++ functional programming yuckiness

Apparently, C++ templates are Turing complete. In theory, that means you can write programs which get run at compile time. So here's a program which calculates the factorial of 8 at compile time:

#include <cstdio>

template <int N>
struct factorial
{
   enum { RET = factorial<N - 1>::RET * N };
};

// Base case - only instantiated when the parameter is 0.
template <>
struct factorial<0>
{
   enum { RET = 1 };
};


int main()
{
   std::printf("%d\n", factorial<8>::RET);
}

That's partly derived from the source code examples for this crazy book about ‘generative programming’.

Some guy has even written a Turing machine using templates.

Of course, you can only use template value parameters that are simple integral values, so you can't do anything interesting or useful like this. But it proves how yucky it is.

< Mysterious Cities of Gold | Playing with mod_perl >

Miniblog

(nuggets of inanity)

Tuesday Apr 24th 2007, 16:54 »
Just took the annual web design survey that AListApart do. I don't realy consider myself to be a web designer, but I have been doing a lot of HTML and CSS lately.
Monday Apr 23rd 2007, 18:23 »
Strange, there appears to be a bare-knuckle boxing match going on in the field outside my flat. Wish they wouldn't make so much noise about it.
Thursday Mar 1st 2007, 18:47 »
“In its written form, Hebrew has no vowels, making it the ideal language for texting.”
—Said in jest on some Radio 4 programme just now.

Archive: 2007 · 2006 · 2005 · 2004
Feed