Template question

Markus Dangl danglm at in.tum.de
Thu Oct 5 13:06:16 PDT 2006


Chad J > schrieb:
> I'm trying to write a template that, when instantiated, gives a value 
> that is the same as the last time it was instantiated plus one.  Here is 
> some code I tried, but it doesn't work:
> 
> import std.stdio;
> 
> template GetUID()
> {
>     const ulong accumulator;
> 
>     static if ( ++accumulator != 0 )
>         const ulong GetUID = accumulator;
>     else
>         static assert(0);
> }
> 
> void main()
> {
>     writefln( GetUID!() ); // should print 1
>     writefln( GetUID!() ); // should print 2
> }
> 
> Hopefully that gives a good idea of what I am shooting for.


This is a bit complicated to explain: Compile time constructs 
(templates) work just like a functional language: They are fully 
deterministic, the only way you can modify the result is by modifying 
the parameters.

If you want to use a counter you'd have to use a recursive approach like 
this:

template counter(uint max, uint i=0)
{
     void initialize()
     {
         writefln(i); // Insert your statement hier
         static if (i<max)
             counter!(max, i+1).initialize();
     }
}

Although that's perhaps not a real speedup compared to initializing the 
program with a counter at runtime...



More information about the Digitalmars-d-learn mailing list