问题
I need a way to store a list of method pointers, but I don't care about what class they belong to. I had this in mind:
struct MethodPointer
{
void *object;
void (*method)(void);
};
Then I could have have a function which takes an arbitrary method:
template <typename T>
void register_method(void(T::*method)(void), T* obj) {
MethodPointer pointer = {obj, method);
}
void use_method_pointer() {
...
MethodPointer mp = ...
// call the method
(mp.object->*method)();
...
}
This obviously doesn't compile because I can't convert the method pointer into a function pointer in register_method().
The reason I need this is because I have a class which can emit events - and I want arbitrary instances to subscribe to these events as method calls. Is this possible to do?
PS. Conditions apply: 1. I don't want to use Boost 2. I don't want to use a 'Listener' interface, where a subscriber have to subclass an abstract interface class.
Thank you for your time.
回答1:
I believe you are just looking for std::function:
using NullaryFunc = std::function<void()>;
Registration:
template <typename T>
void register_method(void(T::*method)(void), T* obj) {
NullaryFunc nf = std::bind(method, obj);
// store nf somewhere
}
Usage:
void use_method() {
...
NullaryFunc nf = ...;
// call the function
nf();
...
}
来源:https://stackoverflow.com/questions/30448056/how-to-store-arbitrary-method-pointers-in-c11