template specialization question

Daniel Murphy yebbliesnospam at gmail.com
Sun Jan 31 11:36:05 PST 2010


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][]);



More information about the Digitalmars-d-learn mailing list