Can't understand templates

Meta via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Nov 29 09:20:41 PST 2014


On Saturday, 29 November 2014 at 11:07:34 UTC, Sly wrote:
> On Saturday, 29 November 2014 at 09:11:51 UTC, Ali Çehreli 
> wrote:
>
>> Point!T getResponse(P : Point!T, T)(string question)
>> {
>>    // ...
>> }
>>
>
> This doesn't work because now this definition has 2 parameters P
> and T. I have to specify both like this: auto pt =
> getResponse!(Point!int, int)("point");  which of course defeats
> the purpose. Otherwise I have ambiguity error:

Not true, T is inferred based on the the type Point has been 
instantiated with, letting you emit the second template argument. 
The following code works:

struct Point(T)
{
	T x;
	T y;
}

P getResponse(P: Point!T, T)(string message)
{
	return P(T.init, T.init);
}

void main()
{
	import std.stdio;
	
         //T is inferred to be int automatically
	writeln(getResponse!(Point!int)("test"));
}


More information about the Digitalmars-d-learn mailing list