c ++:带有任意签名的std :: function的std :: vector [英] c++: std::vector of std::function with arbitrary signatures
问题描述
可以创建一个 std :: vector
,它可以包含任何签名的 std :: function
?
(函数参数都将被预先绑定。)
Is it possible to create an std::vector
that can hold an std::function
with any signature?
(The function arguments would all be pre-bound.)
我尝试了 std :: vector< std :: function< void ()> >
,因为如果我只有一个 std :: function
,我可以绑定任何函数。
I tried std::vector<std::function<void()> >
, since if I only have one std::function
of that type I can bind any function to it.
这似乎在一个向量内部不起作用:如果我试图添加一个函数 std :: bind
除了 void()
之外的签名,我获得:
This does not seem to work inside a vector: if I try to add a function with std::bind
to the vector that has a signature other than void()
, I get:
No matching member function for call to 'push_back'
有办法吗?
编辑:
我记得 std :: function< void )>
允许您绑定返回 void
的任何函数,只要参数使用 std :: bind
,它不允许你绑定任何签名,但为了我的目的它是通用的,所以以下工程:
I just remembered that std::function<void()>
does allow you to bind any function that returns void
as long as the arguments are pre-bound with std::bind
, it does not allow you to bind any signature though, but for my purposes it's generic enough, so the following works:
class A
{
public:
void test(int _a){ return 0; };
};
A a;
std::vector<std::function<void()> > funcArray;
funcArray.push_back(std::bind(&A::test, std::ref(a), 0));
推荐答案
这应该可以工作:
#include <iostream>
#include <functional>
#include <vector>
void hello() { std::cout << "Hello\n"; }
void hello2(const char * name) { std::cout << "Hello " << name << '\n'; }
int main()
{
std::vector<std::function<void()>> v;
v.push_back(hello);
v.push_back(std::bind(hello2, "tim"));
v[0]();
v[1]();
}
如何做?
这篇关于c ++:带有任意签名的std :: function的std :: vector的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!