Template question

Reiner Pope reiner.pope at REMOVE.THIS.gmail.com
Wed Oct 4 19:20:12 PDT 2006

Chad J > wrote:
> 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:
The reason this sort of thing is not supported with templates is that it 
creates ambiguities. Template evaluation is lazy, meaning (a) it is only 
done when it is required, and (b) it can be done in any order. This is 
really the obvious way to do it.

For example, consider the following code:

void foo()
   writefln( GetUID!() );

void bar()
   writefln( GetUID!() );

void main()

Which one prints 1, and which one prints 2? I can think of two arbitrary 
rules which resolve the ambiguity:
1. evaluate all templates from the top of the source code down; or
2. evaluate all templates according to execution order.

The problem is that 1. is arbitrary and contradicts the assumption and 
aim the rearranging the order of functions won't change anything, and 2. 
is not always decidable, vis a vis the halting problem.

I don't actually have an idea of what you are trying to accomplish, 
though. If just simple accumulator, then write it as actual D code and 
let the optimizer inline and pre-evaluate it without your assistance. If 
you want something else, I'm sure there is a way to do it within the 
template system -- you'll probably find Thomas and BCS's suggestions the 
right sort of thing.



More information about the Digitalmars-d-learn mailing list