c++ - C++ 中的 lambda 返回类型

标签 c++ lambda

Lambda with function bodies that contain anything other than a single return statement that do not specify a return type return void.

via 《C++ Primer》 5th Edition, Page 389.

However, if we write the seemingly equivalent program using an if statement, our code won't compile:

//error: can't deduce the return type for the lambda.

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

via 《C++ Primer》 5th Edition, Page 396.

我在 Visual Studio 中编写程序:

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

int main(void) {
    vector<int> vi{ 1, -2, 3, -4, 5, -6 };
    /* Is the return type void? */
    transform(vi.begin(), vi.end(), vi.begin(), [](int i) {
                                                    if (i < 0) return -i;
                                                    else return i; });

    for (int i : vi)
        cout << i << " ";
    cout << endl;

    system("pause");
    return 0;
}

但它可以正确运行。

然后,我在 Visual Studio 中添加了一些语句:

auto f = [](int i) {
                    if (i < 0) return -i;
                    else return i; };

当我将光标移动到 f 时,它显示 f 的返回类型是 int。

这是为什么?

我很困惑。

最佳答案

C++ Primer 5th Edition 涵盖了 C++11,在 C++11 中,您引用的陈述是正确的。然而,C++14 supports deducing return types in more situations ,包括当 lambda 有多个 return 语句时,只要它们都返回相同的类型。大概你的 Visual Studio 版本支持 C++14,或者至少支持它的这个特性。

关于c++ - C++ 中的 lambda 返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40196142/

相关文章:

PHP,用什么代替create_function()?

C++11 Lambda 通过捕获传递

c# - 根据索引从列表中获取项目的 Lambda 表达式

c# - 运行时的 Expression.Lambda 和查询生成,嵌套属性 “Where” 示例

c++ - 替换 dll 驱动程序及其完整性

c++ - 为什么向数据类型不符合表达式的变量提供无效表达式,返回我的 switch 的 default case 语句?

c++ - boost::asio 充满了警告

c++ - Windows 客户端服务器应用程序中的 CreateProcess()

c++ - 多个枚举中的相同名称

java - 具有返回类型的消费者接口(interface)的 lambda 表达式