Can't understand templates

Sly via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Nov 29 00:41:37 PST 2014


Ah, now I see. In C++ we would also need to supply template
parameters, but we'd put them before return type
(template<typename T> getResponse<Point<T>>); in D we put them
before the colon.

Now I'm trying to write a specialization for Pair. It seems that
this is the way to do it:

Pair!(A, B) getResponse(A, B: Pair!(A, B))(string question)
{
      auto a = getResponse!A(" a");
      auto b = getResponse!B(" b");
      return new Pair!(A, B)(a, b);
}

auto pair = getResponse!(Pair!(int, int))("pair?");

But it doesn't work: this call resolves to a general version T
getResponse(T), and I get a compilation error because it tries to
instantiate readf!(Pair*).
What am I doing wrong?

On Saturday, 29 November 2014 at 08:06:33 UTC, Ali Çehreli wrote:
> On 11/28/2014 10:26 PM, Sly wrote:
>
> > I still don't understand how to
> > read this signature:
> > Point!T getResponse(T: Point!T)(string question)
>
> The following is what makes sense to me.
>
> Sorry for going step by step but I think it helped me 
> understand your question. (See item 3 below.)
>
> 1) Point!T is the return type. Although T is unknown at this 
> point, we will wait a little because it may be a template 
> parameter.
>
> Also, according to the syntax of Point!T, Point is apparently a 
> template. So, this function will return the T instantiation of 
> Point, whatever T will be deduced to be in a moment.
>
> 2) getResponse is the name of the function
>
> 3) The first set of parameters is the template parameters:
>
> (T: Point!T)
>
> The meaning: T is a type and this specialization is for Point!T.
>
> Ok, I think I finally understand your original question. I 
> agree that it doesn't make sense to say "T is a type and this 
> specialization is for Point!T". I think we need to read it 
> backward in this case: "This specialization is for Point!T. If 
> so, deduce T from that." So, if getResponse is instantiated 
> with Point!int, then T is deduced to be int.
>
> 4) The instances of this function template take string 
> parameter.
>
> Ali


More information about the Digitalmars-d-learn mailing list