Templates - What's Up with the template keyword?

Mike Parker aldacron at gmail.com
Mon Apr 8 14:56:46 UTC 2019


On Monday, 8 April 2019 at 12:23:28 UTC, Ron Tarrant wrote:

> 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?
>
>

You should have read further along in that chapter :-) I evolve 
the MyTemplate example through the end of that "Templates as code 
blocks" section to this:

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

And show that it must be instantiated like this:

void main() {
   MyTemplate!int.ValWrapper vw1;
   MyTemplate!int.ValWrapper vw2;
   vw1.val = 20;
   vw2.val = 30;
   vw1.printVal();
   vw2.printVal();
}

And in the next section, "Struct and class templates", I 
introduce the concept of eponymous templates by rewriting 
MyTemplate like so:

template ValWrapper(T) {
   struct ValWrapper {
     T val;
     void printVal() {
       writeln("The type is ", typeid(T));
       writeln("The value is ", val);
     }
   }
}

And show that it can be instantiated with the shorthand:

ValWrapper!int vw;

And that the template can be refactored to this (since it's 
eponymous):

struct ValWrapper(T) {
   T val;
   void printVal() {
     writeln("The type is ", typeid(T));
     writeln("The value is ", val);
   }
}

In the subsequent sections, I show both long and short 
(eponymous) forms of enum and function templates.





More information about the Digitalmars-d-learn mailing list