c++11 - 为什么递归 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 会引发错误。谁能告诉我为什么我会收到这个错误?
解决方案
问题不在于 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
}
推荐阅读
- sql - 如何将逗号分隔的 ID 列表转换为他们的名字?
- php - 在移动设备上出现拉伸的缩略图图像 (Magento)
- android - 从 Android Studio 上的 git 导入什么都不做
- vue.js - vuejs - 模板,商店,this.$store 未定义
- java - 创建列表列表
- javascript - JavaScript - 如何在 java 脚本中正确使用``?
- c# - 如何接收 Excel 表格的最后一行?
- asp.net-core - 如何在 .Net Core Blazor 应用程序中创建具有可折叠子菜单的 NavMenu
- javascript - 将 Promise 与 Non-Promise 调用链接时如何避免传播
- python - 不使用内置函数的python最大最小代码问题