Log in

View Full Version : sick template-stuff aka compile-time programs


0rp
February 23rd, 2005, 09:13
Code:
#include <stdio.h>

template<int N> class Factorial
{
public:
enum { value = N * Factorial<N-1>::value };
};

class Factorial<1>
{
public:
enum { value = 1 };
};

int main(int argc, char **args)
{
printf("%d\n", Factorial<10>::value);
return 0;
}


solving algorithms at compiletime
funny shit

dELTA
February 23rd, 2005, 09:38
Hehe, I once wrote a complete executable linker in pure compile-time MASM macro language. It even used self modifying macro code, and produced very nice and compact viral code too... Pffft, two-line factorial solvers...

bilbo
February 23rd, 2005, 12:22
Quote:
[Originally Posted by 0rp]solving algorithms at compiletime

Great example of templates!
In fact the resulting disassembly is simply
Code:

push 375F00h
push "%d"
call _printf


I was asking why in the hell enum had been used... In fact, in the net, you can find also the variant which replaces
Code:

enum { value = N * Factorial<N-1>::value };
enum { value = 1 };

with
Code:

static const int value = N * Factorial<N-1>::value;
static const int value = 1;


Then I understood. It is a bug in Micro$oft (oops... the temp forum $...) compiler! See http://support.microsoft.com/kb/241569/EN-US/

Regards, bilbo