The definition of templates in D

Dmitry Olshansky dmitry.olsh at gmail.com
Sun Mar 18 04:43:18 PDT 2012


On 18.03.2012 15:34, Derek wrote:
> 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 ...
[snip]

Why not this:

template add(X)
{
      auto add(Y,Z)(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!int(u,s)); // --> 467

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

In short: use type parameters when you parametrize on types. Use IFTI to 
avoid typing parameters that could be inferred. X type you cast to, 
clearly can't be inferred from arguments.


>
>
> 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.
>
No just provide type, dummy values smack of flawed dispatch techniques 
from C++ STL.

-- 
Dmitry Olshansky


More information about the Digitalmars-d mailing list