Stephane Wamba
Stephane Wamba

Reputation: 103

Return type deduction of lambda expressions of if-else statements

I'm reading C++ primer 5th edition, chapter 10(lambdas expressions), Here is a program that is intended to replace negative values in a vector by their absolute value.

transform(vi.begin(), vi.end(), vi.begin(),
      [](int i) { if (i < 0) return -i; else return i; });

The author says that:

This code won't compile because the lambda infers the return type as void but we returned a value and to fix this, we must use a trailing return type.

But when I compile this code with GNU GCC Compiler on Windows, it works well.

The author also says that:

This version compile because we need not specify the return type, because that type can be inferred from the type of the conditional operator.

transform(vi.begin(), vi.end(), vi.begin(),
          [](int i) { return i < 0 ? -i : i; });

So, my questions are:

Upvotes: 3

Views: 754

Answers (1)

Edgar Rokjān
Edgar Rokjān

Reputation: 17483

From lambda:

... the return type of the closure's operator() is determined according to the following rules:

  • if the body consists of nothing but a single return statement with an expression, the return type is the type of the returned expression (after lvalue-to-rvalue, array-to-pointer, or function-to-pointer implicit conversion); otherwise, the return type is void. (until C++14)

  • The return type is deduced from return statements as if for a function whose return type is declared auto. (since C++14)

So the author just describes the situation before C++14, since C++14 the code works perfectly.

Upvotes: 7

Related Questions