为什么我不能在C ++ 11中创建一个lambda的向量? [英] Why can't I create a vector of lambda in C++11?

查看:247
本文介绍了为什么我不能在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

直到第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()>)'

我不想要一个函数指针的向量或函数对象的向量。然而,封装了 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; });




我不想要一个函数指针向量或函数向量
对象。

I don't want a vector of function pointers or vector of function objects.

好吧,我想要一个很好的高薪工作,我的梦想,但这不会发生。哦,我也想要一个非常有魅力的妻子,他可以做饭和清洁,因为我真的不能。

Well, I would like a nice high-paying job with a hundred-man developer team to develop all my dreams, but that's not gonna happen either. Oh, and I'd also like a very attractive wife who can cook and clean, since I really can't.

这篇关于为什么我不能在C ++ 11中创建一个lambda的向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆