Template question
Markus Dangl
danglm at in.tum.de
Fri Oct 6 09:59:08 PDT 2006
>> Although that's perhaps not a real speedup compared to initializing the
>> program with a counter at runtime...
>
> could you elaborate with an example I can compile,
> at the moment I don't see how to put it in a working app
>
> thx,
> roel
Here is a full example, it compiles and runs with my DMD 0.168:
=====
module CompileTimeCounter;
import std.stdio;
pragma(msg, "-- This is at compile time");
// Converts an integer i to a string at compile time.
// Needed for pragma(msg).
template itoa(int i)
{
static if (i < 10) const char[] itoa = "0123456789"[i..i+1];
else const char[] itoa = itoa!(i/10) ~ "0123456789"[i%10];
}
// A counter that runs at compile time.
template counter(uint max, uint i=0)
{
void initialize()
{
pragma(msg, itoa!(i));
writefln(i);
static if (i<max)
counter!(max, i+1).initialize();
}
}
// ncounter has to be const, so it is accessible at compile time.
const int ncounter = 10;
int main(char[][]args)
{
writefln("-- This is at run time");
counter!(ncounter).initialize();
return 0;
}
====
As you can see when you're compiling it counts from 0 to 10 (including
10). When you run the resulting exe file, it will also print the numbers
from 0 to 10, but this time there isn't a real counter involved, it's
just like having
writefln(0);
writefln(1);
writefln(2);
...
in your code. To be exact, each writefln() is wrapped up in a seperate
function, this is why i think that a counter at compile time isn't
really efficient.
More information about the Digitalmars-d-learn
mailing list