首页 > 解决方案 > 如果未指定返回类型,则递归 lambda 无法编译

问题描述

下面的代码无法编译(在 gcc9.2 中):

#include<iostream>

int main () {
    auto func = [](auto _func, int n) {
        std::cout << n << '\n';
        if (n > 1) {
            _func(_func, n - 1);
        }
    };
    func(func, 3);
}

除非我指定返回类型如下:

#include<iostream>

int main () {
    auto func = [](auto _func, int n)->void {
        std::cout << n << '\n';
        if (n > 1) {
            _func(_func, n - 1);
        }
    };
    func(func, 3);
}

为什么我们需要在这里显式指定返回类型?

Edit-1:编译错误是:

<source>: In instantiation of 'main()::<lambda(auto:1, int)> [with auto:1 = main()::<lambda(auto:1, int)>]':

<source>:10:17:   required from here

<source>:7:18: error: use of 'main()::<lambda(auto:1, int)> [with auto:1 = main()::<lambda(auto:1, int)>]' before deduction of 'auto'

    7 |             _func(_func, n - 1);

      |             ~~~~~^~~~~~~~~~~~~~

ASM generation compiler returned: 1

标签: c++recursionlambdac++14

解决方案


当我尝试编译它时,我收到以下消息:

main.cpp: In instantiation of 'main()::<lambda(auto:1, int)> [with auto:1 = main()::<lambda(auto:1, int)>]':
main.cpp:10:17:   required from here
main.cpp:7:18: error: use of 'main()::<lambda(auto:1, int)> [with auto:1 = main()::<lambda(auto:1, int)>]' before deduction of 'auto'
    7 |             _func(_func, n - 1);
      |             ~~~~~^~~~~~~~~~~~~~

关键是

错误:在扣除“auto”之前使用“lambda”

一个更简单的例子是

#include<iostream>

auto f(int x) {
    std::cout << x << " ";
    if (x > 0)
        f(x - 1);
}

int main() {
    f(3);   
}

这给出了几乎相同的错误。

本质上,编译器在完成对函数的处理之前无法知道它需要什么返回类型,但它无法完成对函数的处理,直到它计算出f返回的内容。这里有一个循环依赖,所以编译器会报错。

另请参见在 C++14 中扣除 'auto' 之前使用 'auto func(int)'


推荐阅读