首页 > 解决方案 > 为什么递归 lambda 函数与 auto 一起使用时会抛出错误?

问题描述

我正在尝试使用带有 auto 关键字的递归 lambda 函数,如下所示。

#include <iostream>

using namespace std;

int main()
{
    auto func = []()->void{
        static int x = 0;
        cout << x << endl;
        if (x < 5) {
            func();
            x++;
        }
    };

    func();
    return 0;
}

但它抛出编译器错误如下。

main.cpp: In lambda function:
main.cpp:19:13: error: use of ‘func’ before deduction of ‘auto’
             func();
             ^~~~

我知道我们可以用 std::function 实现同样的效果。但我想知道为什么使用“自动”会出错。

我经历了下面的堆栈溢出问题。

但我无法弄清楚为什么在这种情况下使用 lambda 的 auto 会引发错误。谁能告诉我为什么我会收到这个错误?

标签: c++11c++14

解决方案


问题不在于 lambda 表达式的返回类型。问题是 lambda 本身的类型。

每个 lambda 表达式都是唯一的匿名类型。

在您的代码中,编译器知道 lambda 返回 void,但它还不知道 lambda 的类型,因为它还没有完全解析它。

举一个反例来突出这个问题。

#include <iostream>

int main()
{
    int x;
    auto func = [&](){
        // func is going to become an int here, but the compiler does not know that yet
        // it has to parse the whole expression first.
        x = func;
        return 5;
    }(); // <-- calling the lambda and assigning the return value to func
}

推荐阅读