Template question

Chad J "gamerChad\" at spamIsBad gmail.com
Wed Oct 4 20:38:55 PDT 2006


Reiner Pope wrote:
> 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()
> {
>   bar();
>   foo();
> }
> 
> 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.
> 
> Cheers,
> 
> Reiner

I see.  I was kind of expecting arbitrary order of evaluation, but 
didn't care really.  This one was mostly just a learning excercise for 
me to get a better feel for templates.

In a way it would be nice if there was some sort of tutorial type 
resource for D templates; hopefully something that doesn't rely on C++ 
background.  For a long time I just ignored them because they were scary :)

Anyhow, thanks for the info!



More information about the Digitalmars-d-learn mailing list