The definition of templates in D

Derek ddparnell at bigpond.com
Sun Mar 18 04:34:31 PDT 2012


On Sun, 18 Mar 2012 22:00:06 +1100, Derek <ddparnell at bigpond.com> wrote:

>
> The 'adding' is not the point; it could be any functionality. The point  
> I was trying to get across was that it would be useful if the compiler  
> could infer the type parameters of a template instantiation from the  
> types of the data items used in the instantiation reference.

The best I can come up with so far is ...

import std.stdio;
template add(X, Y,Z)
{
      auto add(X c, Y a, Z b)
      {
          return cast(X)a + cast(X)b;
      }
}

void main()
{
      double s;
      int   t;
      ulong u;

      s = 1.23;
      t = 123;
      u = 456;

     writeln(add(t,u,s)); // --> 467

     writeln(add(s,t,s)); // --> 124.23
}


It seems that the templated function's return type is not used when  
searching for matching templates, so I have to explicitly include  
something in the function's signature just to use it as the returned  
data's type.

-- 
Derek Parnell
Melbourne, Australia


More information about the Digitalmars-d mailing list