I'm digging into templates in an attempt to understand the signals-n-slots replacement for the observer pattern, but I've got a question I can't seem to find an answer for and an example for which I'm unable to solve the error.

First, the question...

In Michael Parker's book, "Learning D," (Packt, 2015) on page 160 he gives an example of a basic template:

template MyTemplate(T)
{
   T val;

   void printVal()
   {
      import std.stdio : writeln;
      writeln("The type is ", typeid(T));
      writeln("The value is ", val);
   }
}

But in "Programming in D," (self, 2009-2018) by Ali Çehreli, there's no mention of the 'template' keyword in any of his examples.

Has the 'template' keyword been deprecated? Or is it optional?


And now, my broken code...

In Ali's book (section 64.7, page 401) this example is given:

Point!T getResponse(T : Point!T)(string question)
{
   writefln("%s (Point!%s)", question, T.stringof);
   auto x = getResponse!T(" x");
   auto y = getResponse!T(" y");
   return Point!T(x, y);
}

But I'm having trouble working out how this would be used. Up to this point, either the usage case is given or I was able to work it out on my own, but this one seems to demand a use case outside the scope of what's been covered in the chapter so far and I'm lost.

My full code for this example:

-----------------------------------------
import std.stdio;
import std.math;
import std.string;

struct Point(T)
{
        T x;
        T y;
        
        T distanceTo(Point that) const
        {
                immutable real xDistance = x - that.x;
                immutable real yDistance = y - that.y;
                
immutable distance = sqrt((xDistance * xDistance) + (yDistance * yDistance));
                
                return(cast(T)distance);
                
        } // distanceTo()

} // struct Point


Point!T getResponse(T : Point!T)(string question)
{
        writefln("%s (Point!%s)", question, T.stringof);
        
        auto x = getResponse!T(" x");
        auto y = getResponse!T(" y");
        
        return(Point!T(x, y));
        
} // getResponse() Point!T


void main()
{
auto wayPoint1 = getResponse!Point("Where is the first map location?"); auto wayPoint2 = getResponse!Point("Where is the second map location?");
        
        writeln("Distance: ", wayPoint1.distanceTo(wayPoint2));

} // main()

--------------------------------------
(lines 47 & 48) Error: template instance `getResponse!(Point)` does not match template declaration getResponse(T : Point!T)(string question)

Any help will be very much appreciated.

Reply via email to