lundi 25 mai 2015

How to store arbitrary method pointers in c++11?

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.

Aucun commentaire:

Enregistrer un commentaire