Template question
Don Clugston
dac at nospam.com.au
Thu Oct 5 00:00:00 PDT 2006
Chad J > wrote:
> 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 :)
A tutorial would be nice. I started writing one a while ago, but then
the language changed so much, it became completely obsolete!
And as recently as DMD 0.166, Oskar's patches for member templates have
changed the rules again. Although some 'best practices' are now well
understood, some 'how-tos' are still unknown by everyone. Nobody has
more than 35 days experience with the current D templates. Not even Walter.
<g>
More information about the Digitalmars-d-learn
mailing list