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