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

Why can#39;t I create a vector of lambdas (of the same type) in C++11?(为什么我不能在 C++11 中创建一个 lambda 向量(相同类型)?)
本文介绍了为什么我不能在 C++11 中创建一个 lambda 向量(相同类型)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

限时送ChatGPT账号..

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

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

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)
STL BigInt class implementation(STL BigInt 类实现)
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)