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 which class they belong to. I meant this:

struct MethodPointer
{
    void *object;
    void (*method)(void);
};

Then I could have a function that 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 does not compile because I cannot convert the method pointer to a function pointer in register_method ().

I need this because I have a class that can generate events - and I want arbitrary instances to subscribe to these events as method calls. Can this be done?

PS. The conditions apply: 1. I do not want to use Boost 2. I do not want to use the "Listener" interface, where the subscriber must subclass the abstract class of the interface.

Thank you for your time.

+4
1

, std::function:

using NullaryFunc = std::function<void()>;

:

template <typename T>
void register_method(void(T::*method)(void), T* obj) {
    NullaryFunc nf = std::bind(method, obj);

    // store nf somewhere  
}

:

void use_method() {
    ...
    NullaryFunc nf = ...;
    // call the function
    nf();
    ...
}
+4

All Articles