1Template <typename t>2 classTD;3 4 int&foo () {5 Static intx=0;6 returnx;7 }8 9 intMain () {Ten OneAuto lambda = [] ()Constauto&{returnfoo ();}; ATd<decltype (lambda ()) >dummy; -}
Line 11th, the return value type is deduced according to the const auto& pattern. This is the user-specified way, can be arbitrarily designated as auto before and after can add volatile const & && * * * modifier, as long as can deduce the success of the line.
Of course, you can also specify a specific type:
1Template <typename t>2 classTD;3 4 int&foo () {5 Static intx=0;6 returnx;7 }8 9 intMain () {Ten OneAuto lambda = [] ()Long{returnfoo ();}; ATd<decltype (lambda ()) >dummy; -}
Line 11th, the mandatory return value type is long, as long as Foo () to a long implicit conversion can be OK.
The third is to implement the perfect forwarding by the return value expression. The return value of the function is determined by the actual type of the return value expression, not the distortion.
Template <typename t>class TD; int&& foo () { returnten;} int Main () { return foo ();}; TD<decltype (lambda ()) > dummy;}
This method requires the Decltype (auto) syntax.
If the return value of the function is void (the function body has no return statement; or return F () and void f ();) The following equivalence:
Auto lambda = [] ()-decltype (auto) { = [] ()-auto{ = [] () { };
But the following does not work:
Auto lambda = [] (),const auto{ };
For multiple exit return statements in a function, it is required that each return value expression must be of the same type.
1Template <typename t>2 classTD;3 4 intFoo () {return 1;}5 LongBar () {return 2;}6 7 intMain () {8 9Auto Lambda = []() { Ten returnbar (); One returnfoo (); A }; -Td<decltype (lambda ()) >dummy; -}
The compilation failed because the Foo,bar return value is different. A contradiction was encountered when deriving the return value. Unless you specifically specify a return value:
Template <typename t>class TD; int return 1 ;} Long return 2 ;} int Main () { = [] (),int { return Bar (); return foo (); }; TD<decltype (lambda ()) > dummy;}
In the case of a function recursive invocation, it is required that the first return statement expression in the function body cannot have the existence of a recursive function.
C + + return type deduction