c++ - 如果未指定返回类型,则递归 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
解决方案
当我尝试编译它时,我收到以下消息:
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
返回的内容。这里有一个循环依赖,所以编译器会报错。
推荐阅读
- javascript - 谷歌表打卡
- javascript - 从 HTML(静态)迁移到 WP 后联系表单不起作用
- python-3.x - Windows 10 上的 Python 3.7.0 使用 open() 出现意外行为
- amazon-web-services - Cognito/Pinpoint 集成 - 缺乏特定于用户的数据
- python - 这是什么日期时间格式以及如何解析它?
- python - Kivy 如何在 kivy 中从字典创建小部件
- ember.js - ember 成员操作规范化响应
- azure - Azure KeyVault 访问策略 - 使用 Powershell 和 VSTS 添加应用服务
- c# - ASP.NET MVC 表单身份验证域属性在 Firefox 中中断登录
- excel - 使用 VBA 单击下拉菜单上的项目