为什么我不能在C ++ 11中创建Lambda向量(相同类型)?
我试图创建lambda向量,但失败了:
I was trying to create a vector of lambda, but failed:
auto ignore = [&]() { return 10; }; //1
std::vector<decltype(ignore)> v; //2
v.push_back([&]() { return 100; }); //3
Up to line #2, it compiles fine. But the line#3 gives compilation error:
错误:没有匹配函数调用'std :: vector< main()::< lambda()>> :: push_back(main()::< lambda()>)'
error: no matching function for call to 'std::vector<main()::<lambda()>>::push_back(main()::<lambda()>)'
我不需要功能指针的向量或功能对象的向量.但是,封装 real lambda表达式的功能对象的矢量对我来说将是有效的.这可能吗?
I don't want a vector of function pointers or vector of function objects. However, vector of function objects which encapsulate real lambda expressions, would work for me. Is this possible?
每个lambda都有不同类型—即使它们具有相同的签名.如果要执行类似的操作,则必须使用运行时封装容器,例如std::function
.
Every lambda has a different type—even if they have the same signature. You must use a run-time encapsulating container such as std::function
if you want to do something like that.
例如:
std::vector<std::function<int()>> functors;
functors.push_back([&] { return 100; });
functors.push_back([&] { return 10; });