template specialization question
daoryn
poreas at asiot.po
Mon Feb 1 14:13:04 PST 2010
Daniel Murphy Wrote:
> daoryn Wrote:
>
> > According to http://digitalmars.com/d/2.0/template.html it is possible to specify template specialization so that DMD prefers them when instanciating templates, however the following code:
> >
> >
> > ---------------------------------
> > import std.stdio;
> >
> > void print(T)(T thing)
> > {
> > writeln("Calling print(T)");
> > writeln(T.stringof);
> > }
> >
> > void print(T:T[])(T[] things)
> > {
> > writeln("Calling print(T[])");
> > writeln(T.stringof);
> > }
> >
> > void main()
> > {
> > print(3);
> > print([1,2,3]);
> > }
> >
> > -----------------------------------------
> >
> > will output:
> >
> > Calling print(T)
> > int
> > Calling print(T)
> > int[3u]
> >
> > I expected it to output "calling print(T[])" on the second "print". Would this be a bug or did I misunderstand the template specialization?
> >
>
> It looks like the type of the array literal is a static array, not a dynamic one.
> Static arrays can be matched with the following specification:
> void print(T : U[N], U, size_t N)(T things)
> Or you could use the slice operator to transform the static array into a dynamic one.
> eg print([1,2,3][]);
>
Sadly, your solution doesnt apply. The used template is still the wrong one.
Code:
void print(T)(T thing)
{
writeln("Calling print(T)");
writeln(T.stringof);
}
void print(T:T[])(T[] things)
{
writeln("Calling print(T[])");
writeln(T.stringof);
}
void main()
{
print(3);
print([1,2,3][]);
}
---------------
output:
Calling print(T)
int
Calling print(T)
int[]
NOTE: DMD2.040 used.
More information about the Digitalmars-d-learn
mailing list