c++ - 如果未指定返回类型,递归 lambda 将无法编译

标签 c++ recursion lambda c++14

以下代码无法编译(在 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

最佳答案

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

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);
      |             ~~~~~^~~~~~~~~~~~~~

关键是

error: use of 'lambda' before deduction of 'auto'

一个更简单的例子是这样的

#include<iostream>

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

int main() {
    f(3);   
}

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

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

另请参阅Use of 'auto func(int)' before deduction of 'auto' in C++14 .

关于c++ - 如果未指定返回类型,递归 lambda 将无法编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59656412/

相关文章:

Java 8 Stream API 相当于嵌套 for 循环

python - 如何使这个 lambda 在 Python3 中正常工作?

Javascript递归数组展平

c++ - 错误 : 'new' cannot appear in a constant-expression

带有 'const' 的 C++ 模板

c++ - 拖放操作后事件不起作用

algorithm - 计算将数字分成 4 部分的方法数

c++ - 在 3d 棋盘中查找水量的提示

c# - 如何使用表达式检查 !=null 针对用户定义的数据类型?

c++定时相同的循环给出不同的结果