为什么我不能在 C++11 中创建一个 lambda 向量(相同类型)?

2021-12-21 00:00:00 lambda vector c++ c++11

我试图创建一个 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

直到第 2 行,它编译良好.但是第 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; });

相关文章