According with the comments, you can use either std::function
or a structure similar to the one proposed here.
It follows a minimal and working example of the second suggestion:
class Dispatcher {
Dispatcher() { }
template<class C, void(C::*M)() = C::receive>
static void invoke(void *instance) {
(static_cast<C*>(instance)->*M)();
}
public:
template<class C, void(C::*M)() = &C::receive>
static Dispatcher create(C *instance) {
Dispatcher d;
d.fn = &invoke<C, M>;
d.instance = instance;
return d;
}
void operator()() {
(fn)(instance);
}
private:
using Fn = void(*)(void *);
Fn fn;
void *instance;
};
struct S {
void receive() { }
};
int main() {
S s;
Dispatcher d = Dispatcher::create(&s);
d();
};
Note that it has to be modified accordingly with your requirements (currently, the targeted member method has no return value and does not accept arguments).
Also, it can be easily extended to store an array of target member methods, that is what you were looking for: simply store a vector of pairs of instance
s and invoke
functions.
In addition, you can use variadic template with the Dispatcher
function to let it be more flexible. This way, you'll be able to define Dispatcher
s having different return types and arguments lists.
EDIT
It follows an example of a Dispatcher
that accepts more than one target member function.
To extend it by means of variadic template as above mentioned is still quite easy.
#include <vector>
#include <utility>
class Dispatcher {
template<class C, void(C::*M)() = C::receive>
static void invoke(void *instance) {
(static_cast<C*>(instance)->*M)();
}
public:
template<class C, void(C::*M)() = &C::receive>
void bind(C *instance) {
auto pair = std::make_pair(&invoke<C, M>, instance);
targets.push_back(pair);
}
void operator()() {
for(auto pair: targets) {
(pair.first)(pair.second);
}
}
private:
using Fn = void(*)(void *);
std::vector<std::pair<Fn, void*>> targets;
};
struct S {
void receive() { }
};
struct T {
void receive() { }
};
int main() {
S s;
T t;
Dispatcher d;
d.bind(&s);
d.bind(&t);
d();
};
Please note that in the examples above there is no guarantee that the pointer submitted as instance
is still valid once actually used. You should either take care of the lifetime of your bound objects or slightly modify the example in order to introduce a more safer handle.