template specialization question

daoryn poreas at asiot.po
Mon Feb 1 14:31:37 PST 2010


Tomek Sowiński Wrote:

> Dnia 31-01-2010 o 21:39:21 Ali Çehreli <acehreli at yahoo.com> napisał(a):
> 
> > � 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.
> 
> It's high time I upgraded, then.
> 
> > 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
> 
> Or even simpler:
> void print(T)(T[] things)
> 
> But that's "regular" not template overloading.
> 
> 
> Tomek

The "is" solution is simpler if one uses the "isArray!()" from std.traits. The function can then be correctly implemented but the original issue remains: is it a compiler bug or misinterpretation of the spec?

Adding an additional hidden type is just awkward when simpler solutions exist (and are advertised on the spec). Why go into the clutter of conditional compilation if simple template overloading should work?


More information about the Digitalmars-d-learn mailing list