Return deduction type

Possible duplicate:
Omit return type in C ++ 11

In C ++ 11, lambda can infer its return type if the body consists only of a return statement. A suggestion is work to remove this restriction and, apparently, it already works in GCC.

Is there a reason this cannot be extended to all returned auto functions?
Has this extension been already proposed?

+4
c ++ c ++ 11
source share
2 answers

Is there a reason why this cannot be extended to all automatic return functions?

Well, there is the fact that this would not be possible if the function was not defined right there (and not just a declaration). You will lose the ability to forward ads for such features.

In addition, functions do not return auto . auto before defining a function is a purely syntactic thing that allows returning return types. And the only reason the return type is specified last is because it can refer to function arguments (usually for a template and decltype ). Functions still return a specific value.

+3
source share

There really is a reason.

Namely, the function name is inside the scope inside the function, but not in the specification of the trailing-return type. Lambdas are freed up because they have no names, although I think that the variable initialized from lambda, entered by inference, is also in scope, so they already suffer this problem even with the standard syntax ( workaround ).

With the name of the function in scope, you can build an infinite circular dependence. eg.

 auto fact(int n) { return (n > 0)? n*fact(n-1): 1; } 

In this case, typing is consistent for several variants of the return type ... int , long long , float and double , as well as std::complex<double> , etc.

There is no problem with trailing-return-type, the code is simply illegal:

 auto fact(int n) -> decltype((n > 0)? n*fact(n-1): 1) /* unknown identifier fact */ 

In another example, this contradicts any choice of return type:

 auto f(int a) { char r[sizeof(f(a))+1]; return r; } 

What does your new and improved g ++ do with this?

 auto fact = [&](int n){ return (n > 0)? n*fact(n-1): 1; }; 
+1
source share

All Articles