Thread overview
template specialization
Mar 04, 2007
Thorsten
Mar 04, 2007
Thorsten Kiefer
Mar 05, 2007
Sean Kelly
Mar 04, 2007
Thorsten Kiefer
March 04, 2007
Hi, when I compile this :

template toString(T) {
	char[] toString(T x){
		return "<??>";
	}
}
template toString(T : T[]) {
	char[] toString(T[] x){
		return "<array>";
	}
}

, I get this : tools.d(162): template tools.toString(T : T[]) specialization not allowed for deduced parameter T

According to the online manual this should be no error.
How can I solve this ?

March 04, 2007
"Thorsten" <thorstenkiefer@gmx.de> wrote in message news:esd2dn$126l$1@digitalmars.com...
> , I get this :
> tools.d(162): template tools.toString(T : T[]) specialization not allowed
> for deduced parameter T
>
> According to the online manual this should be no error.
> How can I solve this ?

You are instantiating this template implicitly, as:

char[] s = toString([1, 2, 3]);

The spec says "Function template type parameters that are to be implicitly deduced may not have specializations."


March 04, 2007
OK, I solved it that way :

char[] toString(T)(T x){
	static if(is(T B == B[])) {
		char[] s;
		s ~= '[';
		if(x.length > 0){
			s ~= toString(x[0]);
			foreach(y;x[1..$]){
				s ~= ',';
				s ~= toString(y);
			}
		}
		s ~= ']';
		return s;
	} else {
		return std.string.toString(x);
	}
}

March 04, 2007
Jarrett Billingsley Wrote:
> The spec says "Function template type parameters that are to be implicitly deduced may not have specializations."

And why is that ? The type parameters could be deduced and then the best specialization could be used. Why do they exclude each other ?
March 04, 2007
Thorsten Kiefer wrote:
> OK, I solved it that way :
> 
> char[] toString(T)(T x){
> 	static if(is(T B == B[])) {
> 		char[] s;
> 		s ~= '[';
> 		if(x.length > 0){
> 			s ~= toString(x[0]);
> 			foreach(y;x[1..$]){
> 				s ~= ',';
> 				s ~= toString(y);
> 			}
> 		}
> 		s ~= ']';
> 		return s;
> 	} else {
> 		return std.string.toString(x);
> 	}
> }
> 

You could also get this same effect just by calling std.string.format(), which as I recall formats arrays in precisely this way.

format("%s", [1, 2, 3]) => "[1, 2, 3]"

(Admittedly its been a little while since I used Phobos, though.)

-- Chris Nicholson-Sauls
March 05, 2007
Jarrett Billingsley wrote:
> "Thorsten" <thorstenkiefer@gmx.de> wrote in message news:esd2dn$126l$1@digitalmars.com...
>> , I get this :
>> tools.d(162): template tools.toString(T : T[]) specialization not allowed for deduced parameter T
>>
>> According to the online manual this should be no error.
>> How can I solve this ?
> 
> You are instantiating this template implicitly, as:
> 
> char[] s = toString([1, 2, 3]);
> 
> The spec says "Function template type parameters that are to be implicitly deduced may not have specializations." 

Really?  I'm almost sure I've done this before too.  How weird.


Sean