Template question

rm roel.mathys at gmail.com
Fri Oct 6 08:58:23 PDT 2006


Markus Dangl wrote:
> 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...

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



More information about the Digitalmars-d-learn mailing list