template condition

Steven Schveighoffer schveiguy at yahoo.com
Thu Sep 27 09:11:38 PDT 2012


On Thu, 27 Sep 2012 11:46:05 -0400, Namespace <rswhite4 at googlemail.com>  
wrote:

> On Thursday, 27 September 2012 at 15:39:39 UTC, Steven Schveighoffer  
> wrote:
>> On Thu, 27 Sep 2012 11:34:15 -0400, Namespace <rswhite4 at googlemail.com>  
>> wrote:
>>
>>> Ok. And there is no performance difference? Just for the sake of  
>>> completeness. :)
>>
>> performance where?  Template instantiation is done at compile time.
>>
>> The resulting code should be unaffected runtime-performance wise.
>>
>> -Steve
>
> I mean: is there any difference by building the template? I don't  
> understand what "more flexible" exactly mean.

The constraint basically is saying whether to instantiate the template or  
not, it has little to do with runtime performance.

Flexible means you have a full boolean logic you can use.

For example, if you had two unrelated objects A and B, how would you  
instantiate a template if the parameter derives from A *or* derives from B?

With a template constraint, that's:

template tmp(T) if(is(T : A) || is(T : B))

This is impossible to do with a specialization.

However, there are some limitations.  Template constraints don't cascade,  
while specializations do.

So while this:

template tmp(T) ...
template tmp(T : A)

works fine, this:

template tmp(T) ...
template tmp(T) if (is(T : A)) ...

does not, because it can instantiate both with an A.  Instead you have to  
do:

template tmp(T) if(!is(T : A)) ...
template tmp(T) if(is(T : A)) ...

It has been proposed to try and use else (if), but Walter didn't like it.

-Steve


More information about the Digitalmars-d-learn mailing list