Return if-else lambda表达式的类型推导

Return type deduction of lambda expressions of if-else statements

我正在阅读 C++ primer 第 5 版第 10 章(lambda 表达式),这是一个旨在用绝对值替换向量中的负值的程序。

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

作者说:

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.

但是当我在 Windows 上使用 GNU GCC 编译器编译这段代码时,它运行良好。

作者还说:

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; });

那么,我的问题是:

来自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)

所以作者只是描述了C++14之前的情况,因为C++14代码完美运行。