如何在 C++11 中存储任意方法指针?

mrm*_*vin 4 c++ store member-function-pointers list c++11

我需要一种方法来存储方法指针列表,但我不在乎它们属于哪个类。我想到了这一点:

struct MethodPointer
{
    void *object;
    void (*method)(void);
};
Run Code Online (Sandbox Code Playgroud)

然后我可以有一个采用任意方法的函数:

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)();

    ...
}
Run Code Online (Sandbox Code Playgroud)

这显然无法编译,因为我无法在 register_method() 中将方法指针转换为函数指针。

我需要这个的原因是因为我有一个可以发出事件的类 - 我希望任意实例订阅这些事件作为方法调用。这是可能的吗?

附注。适用条件: 1. 我不想使用 Boost 2. 我不想使用“侦听器”接口,其中订阅者必须对抽象接口类进行子类化。

感谢您的时间。

Bar*_*rry 5

我相信你只是在寻找std::function

using NullaryFunc = std::function<void()>;
Run Code Online (Sandbox Code Playgroud)

登记:

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

    // store nf somewhere  
}
Run Code Online (Sandbox Code Playgroud)

用法:

void use_method() {
    ...
    NullaryFunc nf = ...;
    // call the function
    nf();
    ...
}
Run Code Online (Sandbox Code Playgroud)