On 03/18/12 12:34, Derek wrote: > On Sun, 18 Mar 2012 22:00:06 +1100, Derek <ddparn...@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. >
You can either let the compiler figure out the right common type or give it explicitly: auto add(X=void,Y,Z)(Y a, Z b) { static if (is(X==void)) alias typeof(a+b) RX; else alias X RX; return cast(RX)a + cast(RX)b; } Both "add(u,s)" and "add!int(u,s)" will work; note that the first version returns a 'double', but that's probably what you want, when not explicitly asking for an 'int'. artur