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

为君一笑 提交于 2019-12-23 15:02:22

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!