如何在C ++ 11中存储任意方法指针? [英] 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)();
...
}
这显然无法编译,因为我无法在register_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.适用条件: 1.我不想使用Boost 2.我不想使用监听器"接口,订户必须将抽象接口类作为子类.
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.
谢谢您的时间.
推荐答案
我相信您只是在寻找 std::function
:
I believe you are just looking for 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();
...
}
这篇关于如何在C ++ 11中存储任意方法指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!