指向具有多个对象的成员函数的指针的向量C ++ [英] Vector of pointers to member functions with multiple objects c++
问题描述
考虑以下代码:
class A
{
public:
void aFoo() {}
};
class B
{
public:
void bFoo() {}
};
class C
{
public:
void c1Foo() {}
void c2Foo() {}
};
不管代码体系结构如何,即使那些成员函数在多个类中,也可以创建指向成员函数的指针的向量吗?
Regardless the code architecture, is it possible to create a vector of pointers to member functions even if those functions are in multiple classes ?
在这种情况下,继承不是解决方案,因为我们不知道我们要在一个类中使用多少个函数(类C有两个函数).但是我们知道它们都有相同的原型.
In this case, inheritance is not a solution because we don't know how many functions we want to use in a class (class C has two functions). But we know they all have the same prototype.
推荐答案
不同类的成员函数具有不同的类型.因此,为了拥有任何同质容器(例如 std :: vector
或 std :: array
),您需要将它们包装在某种可以表示的值类型中它们全部(例如 boost :: variant
或 boost :: any
).
Member functions of different classes have different types. So in order to have any homogeneous container (like std::vector
or std::array
) of those you'll need to wrap them in some value type that may represent them all (like boost::variant
or boost::any
).
另一方面,如果您需要的只是特定类型的成员函数(例如 void()
),并且您不介意事先传递应在其上调用它们的对象,那么您就可以将它们存储为 std :: function< void()>
(对于此特定示例),并在对其进行存储之前只调用 std :: bind
容器.
On the other hand if all you need are member functions of a specific type (for example void()
) and you don't mind passing the object on which they should be called before hand, then you can just store them as std::function<void()>
(for this specific example) and just call std::bind
on them before storing them in the container.
作为一个例子,给出:
A a; B b; C c;
std::vector<std::function<void()>> vector {
std::bind(&A::aFoo, a),
std::bind(&B::bFoo, b),
std::bind(&C::c1Foo, c),
std::bind(&C::c2Foo, c)
};
您可以致电:
for (auto fn : vector)
fn();
这篇关于指向具有多个对象的成员函数的指针的向量C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!