c++ - 在基于范围的循环中使用 lambda 的初始化列表

标签 c++ c++11

使用 gcc 4.9 -std=c++14,我尝试制作一个 lambda vector :

vector<function<void ()>> v = {[]{cout << "foo";}, []{cout << "bar";}};
for (auto&& a: v) a();

而且效果很好。然后我尝试将 lambda 的初始化列表直接传递给基于范围的 for:

for (auto&& a: {[]{cout << "foo";}, []{cout << "bar";}}) a();

我得到了:

error: unable to deduce 'std::initializer_list<auto>&&' from '{<lambda closure object>main()::<lambda()>{}, <lambda closure object>main()::<lambda()>{}}'

从错误消息的外观来看,我大胆猜测可能是因为“lambda 闭包对象”是内置语言术语,而不是 std::的直接等价物函数(所以没有真正的类型)。

这背后的深层原因是什么?此外,这可能与实现相关,还是规范规定了这种行为?

最佳答案

每个 lambda 都有自己独特的类型。因此,您不能从不同类型的 lambda 构建 std::initializer_list。

根据 C++ 标准(5.1.2 Lambda 表达式)

3 The type of the lambda-expression (which is also the type of the closure object) is a unique, unnamed nonunion class type — called the closure type — whose properties are described below.

还有

6 The closure type for a non-generic lambda-expression with no lambda-capture has a public non-virtual nonexplicit const conversion function to pointer to function with C++ language linkage (7.5) having the same parameter and return types as the closure type’s function call operator.

关于c++ - 在基于范围的循环中使用 lambda 的初始化列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27593001/

相关文章:

c++ - 循环中的模板元编程?

c++ - C++ 中的继承构造函数

c++ - 使用较小的默认对齐方式重载 operator new

隐式构造函数中未检查 C++11 初始值设定项列表长度

c++ - 递归函数中的许多参数会导致性能问题吗?

c++ - sstream : No such file or directory

c++ - 将 OpenMP 添加到程序中以计算 n x n 矩阵 n x n 的行列式

c++ - 声明一个继承final的类

c++ - 如何将 Qt 集成到现有的应用程序开发工作流程中?

c++ - 如何在 unordered_map 中设置值并确定是否添加了新键