template specialization question
Ali Çehreli
acehreli at yahoo.com
Sun Jan 31 12:39:21 PST 2010
� wrote:
> Dnia 31-01-2010 o 20:59:47 Tomek Sowi�ski <just at ask.me> napisa�(a):
>
>> // specialization needed to limit matching types
>> void print(T:int)(T thing)
>
> To be clear -- I did this to silence the compiler saying the call with
> array matches more than one function template declaration. I'm not sure
> whether the compiler is right -- it has a print specifically for arrays
> so it should be picked over plain print(T) as it's more specialized...
> any template expert here?
>
>
> Tomek
It works with dmd 2.040 without the :int specialization.
Also, for variety, i've used the 'is' expression as described here
http://digitalmars.com/d/2.0/expression.html#IsExpression
for "conditional compilation" in the program below. I think
specialization vs. conditional compilation differ semantically this way
(no expert here! :) ):
specialization: Use this definition for T matching U[]
is expression: Consider this definition only for T matching U[]
The effect should be the same in this case; but it feels like there must
be a difference. :)
import std.stdio;
void print(T)(T thing)
{
writeln("Calling print(T)");
writeln(T.stringof);
}
// T is an array of any Us.
void print(T, U)(T things)
if (is (T == U[])) // <-- is expression
{
writeln("Calling print(T[])");
writeln(T.stringof);
}
void main()
{
print(3);
print([1,2,3]);
}
Also it could be is (T : U[]) as well, which differs from is (T == U[])
as explained at the link above.
Ali
More information about the Digitalmars-d-learn
mailing list