Considering this following code :
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 ?
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.
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).
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.
As an example, given:
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)
};
you would be able to call:
for (auto fn : vector)
fn();
Live demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With