Why can#39;t I create a vector of lambdas (of the same type) in C++11?(为什么我不能在 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 行,它编译良好a>.但是第 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 向量(相同类型)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么我不能在 C++11 中创建一个 lambda 向量(相同类型)?
基础教程推荐
- CString 到 char* 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
