www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Infer return type from assignment

reply ixid <nuaccount gmail.com> writes:
Is it possible to infer a template's return type from what it's 
assigned to? If not is this a difficult or worthless feature to 
add?

OUT fun(IN, OUT)(IN value) {
     return value.to!OUT;
}

void main() {
     float a = 5.0;
     int b = fun(a);
}
Apr 11 2018
next sibling parent reply Adam D. Ruppe <destructionator gmail.com> writes:
On Wednesday, 11 April 2018 at 14:26:53 UTC, ixid wrote:
 Is it possible to infer a template's return type from what it's 
 assigned to? If not is this a difficult or worthless feature to 
 add?
Not really. The function call needs to make sense by itself: fun(a) needs to be a complete thing for a lot of things in the language to work. Type checking assumes it is there, inference assumes it is there, overloading assumes it s there, etc. void foo(int); void foo(float); foo(fun(a)); // what happens? So I don't say anything is impossible that isn't a paradox... but the effort level to solve all these problems would be really high for D.
Apr 11 2018
parent ixid <nuaccount gmail.com> writes:
On Wednesday, 11 April 2018 at 14:33:06 UTC, Adam D. Ruppe wrote:
 On Wednesday, 11 April 2018 at 14:26:53 UTC, ixid wrote:
 Is it possible to infer a template's return type from what 
 it's assigned to? If not is this a difficult or worthless 
 feature to add?
Not really. The function call needs to make sense by itself: fun(a) needs to be a complete thing for a lot of things in the language to work. Type checking assumes it is there, inference assumes it is there, overloading assumes it s there, etc. void foo(int); void foo(float); foo(fun(a)); // what happens? So I don't say anything is impossible that isn't a paradox... but the effort level to solve all these problems would be really high for D.
I am sure there are all sorts of thorns involved but for your example a somewhat arbitrarily defined fallback hierarchy of types from most complex to most simple, with it matching the most 'simple' that it can.
Apr 11 2018
prev sibling parent Steven Schveighoffer <schveiguy yahoo.com> writes:
On 4/11/18 10:26 AM, ixid wrote:
 Is it possible to infer a template's return type from what it's assigned 
 to? If not is this a difficult or worthless feature to add?
 
 OUT fun(IN, OUT)(IN value) {
      return value.to!OUT;
 }
 
 void main() {
      float a = 5.0;
      int b = fun(a);
 }
Sort of: void fun(IN, OUT)(IN value, out OUT result) { result = value.to!OUT; } Other than that, it doesn't work. -Steve
Apr 11 2018