Can't understand templates

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Nov 29 01:11:50 PST 2014


On 11/29/2014 12:41 AM, Sly wrote:
> 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?

I wish I could formalize these definitions better or consistently but 
here my "art", which works: :)

Pair!(A, B) getResponse(P : Pair!(A, B), A, B)(string question)
{
     // ...
}

That template parameter reads:

- This template takes a single parameter (P)

- P must match Pair!(A, B)

- Where A and B are both types

So, getting back to Point, now the following is consistent with the above:

Point!T getResponse(P : Point!T, T)(string question)
{
     // ...
}

Now, that means: "This is a specialization for P, where it matches 
Point!T and T is a type."

Maybe I should change the specialization examples in that chapter...

Ali



More information about the Digitalmars-d-learn mailing list