+1 vote
in C Plus Plus by
C++14 feature- Function return type deduction

1 Answer

0 votes
by
C++11 allowed lambda functions to deduce the return type based on the type of the expression given to the return statement. C++14 provides this ability to all functions. It also extends these facilities to lambda functions, allowing return type deduction for functions that are not of the form return expression;.[3]

In order to induce return type deduction, the function must be declared with auto as the return type, but without the trailing return type specifier in C++11:

auto DeduceReturnType();   // Return type to be determined.

If multiple return expressions are used in the function's implementation, then they must all deduce the same type.[4]

Functions that deduce their return types can be forward declared, but they cannot be used until they have been defined. Their definitions must be available to the translation unit that uses them.

Recursion can be used with a function of this type, but the recursive call must happen after at least one return statement in the definition of the function:[4]

auto Correct(int i)

{

  if (i == 1)

    return i;             // return type deduced as int

  return Correct(i-1)+i;  // ok to call it now

}

auto Wrong(int i)

{

  if (i != 1)

    return Wrong(i-1)+i;  // Too soon to call this. No prior return statement.

  return i;               // return type deduced as int

}

Related questions

+1 vote
asked Jan 4, 2020 in C Plus Plus by AdilsonLima
+1 vote
+1 vote
asked Jan 4, 2020 in C Plus Plus by AdilsonLima
...