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... )
Comments 5
Reply
(I think your are short some arithmatic)
Welcome to the wonderful world of templates. I'm still learning
Reply
Reply
Reply
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