Meta

Jan 10, 2008 08:15

It's really dumb, but it's my most proud hack:

// meta.C

#include

template <>
inline printN<1>(const char * msg) {
printf("%s", msg);
}

template
inline printN(const char * msg) {
printN<1>(msg);
printN(msg);
}

int main() {
printN<3>("Hello World!\n");
return 0;
}
Points for figuring out what it does; double-plus points for knowing ( Read more... )

Leave a comment

Comments 5

quatch January 10 2008, 16:33:09 UTC
I don't remember templates at all, but is this some sort of recusion?

Reply


daunicorn January 10 2008, 18:07:05 UTC
I think it prints "Hello World!\n" infintly.

(I think your are short some arithmatic)

Welcome to the wonderful world of templates. I'm still learning

Reply

dysan27 January 10 2008, 22:08:59 UTC
That's what I was going to say, as long as the number passed is not 1.

Reply


lindiril January 14 2008, 10:23:42 UTC
You guys suck. You should be astute enough to take into account the unintended typo. Seriously, guys. Seriously.

Reply


changeinwatrloo January 14 2008, 10:44:49 UTC
Well, I don't blame anyone for not getting it correct, since there was indeed a typo. I didn't escape some of the <> signs, so your browser-and mine-threw out the as a tag it doesn't understand.

Anyway, what this does is print "Hello World!\n" N times, inline. That is, the compiled code does not contain a printN method nor a loop. Just the code to print "Hello World!\n" three times in the main method.

Why that's dumb: To get g++ to even consider the inline keyword you have to have optimizations turned on, and when that's the case it'll also try to unroll loops so the following should be equivalent to the above:

for (unsigned int i = 0; i < 3; i += 1) {
printf("%s", msg);
}

The cool part is not so much how this is done-it's just recursion-but that there's a way to state the recursive base case. The first printN method basically says, "This is the code for printN<1>. When N is 1 don't use the other method."

So! You and I now know how to do compile-time recursion with templates.

Reply


Leave a comment

Up