我试图创建一个 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 向量(相同类型)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
fpermissive 标志有什么作用?What does the fpermissive flag do?(fpermissive 标志有什么作用?)
如何在我不想编辑的第 3 方代码中禁用来自 gccHow do you disable the unused variable warnings coming out of gcc in 3rd party code I do not wish to edit?(如何在我不想编辑的第 3 方代码中禁
使用 GCC 预编译头文件Precompiled headers with GCC(使用 GCC 预编译头文件)
如何在 OS X 中包含 omp.h?How to include omp.h in OS X?(如何在 OS X 中包含 omp.h?)
如何让 GCC 将 .text 部分编译为可写在 ELF 二进制文How can I make GCC compile the .text section as writable in an ELF binary?(如何让 GCC 将 .text 部分编译为可写在 ELF 二进制文件中?)
GCC、字符串化和内联 GLSL?GCC, stringification, and inline GLSL?(GCC、字符串化和内联 GLSL?)