使用 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/