www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Return type inference on template

reply Andrea Fontana <advmail katamail.com> writes:
Simple template:

T test(T)() { return T.init; }

This code give error:

int myVar;
myVar =3D test();

Why? Can't compiler guess T =3D=3D int?
Jul 10 2012
parent Timon Gehr <timon.gehr gmx.ch> writes:
On 07/10/2012 04:14 PM, Andrea Fontana wrote:
 Simple template:

 T test(T)() { return T.init; }

 This code give error:

 int myVar;
 myVar = test();

 Why? Can't compiler guess T == int?
Type deduction only proceeds in the direction the data flows. Reversing this process would in principle work in a few cases, such as the one you present here. I think it would be neat to have more powerful IFTI. An even more important improvement would be to allow parameters to cross-talk, eg: auto map(R,S,T...)(R range, S delegate(ElementType!R) dg) { ... } [1,2,3].map(x=>2*x); // currently an error, but could be made to work Note that full type inference cannot be achieved in D, because the type system is Turing complete.
Jul 10 2012