C ++中的lambda返回类型

时间:2016-10-22 19:24:46

标签: c++ lambda

  

Lambda,其函数体包含除单个之外的任何内容   不指定返回类型的return语句返回void。

     

通过“C ++ Primer”第5版,第389页。

     

但是,如果我们使用if编写看似等效的程序   声明,我们的代码不会编译:

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

通过“C ++ Primer”第5版,第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。

为什么会这样?

我很困惑。

1 个答案:

答案 0 :(得分:9)

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