我想在一个类中创建一个自定义事件处理程序,并传递另一个类的功能。
class EventArgs
{
};
class one
{
public:
typedef void(EventHandler)(EventArgs* e);
void RegisterFunction(EventHandler* f);
private:
list<EventHandler*>function_list;
};
class two
{
public:
two();
private:
void FunctionEvent(EventArgs* e);
};
two::two()
{
one on;
on.RegisterFunction(&FunctionEvent);
}
错误代码为: 没有匹配的函数可以调用“ one :: RegisterFunction(void(void(two :: )EventArgs )))”。RegisterFunction(&FunctionEvent);
如果FunctionEvent()不像这样工作,则不属于第二类:
void FunctionEvent(EventArgs* e)
{
}
int main()
{
one on;
on.RegisterFunction(&FunctionEvent);
}
有什么区别?
答案 0 :(得分:0)
在所有情况下都可以使用的最简单,最通用的方法是使用std::function
。它真的很容易使用,并且就像常规函数一样工作。此外,std::function
与lambads,函数指针一起使用,并且与std::bind
一起使用时,甚至可以与成员函数一起使用。
对于您的特殊情况,我们希望使EventHandler
成为接受EventArgs*
并且不返回任何内容的函数:
using EventHandler = std::function<void(EventArgs*)>;
从lambda或函数指针创建它真的很容易:
// Create it from a lambda
EventHandler x = [](EventArgs* args) { /* do stuff */ };
void onEvent(EventArgs* args) {}
EventHandler y = &onEvent; // Create it from function pointer
此外,您可以使用std::bind
通过成员函数创建它:
// Create it from a member function
struct MyHandler {
void handleEvent(EventArgs* args);
};
MyHandler handler;
EventHandler z = std::bind(&MyHandler::handleEvent, handler);
class one
{
public:
// Use std::function instead of function pointer
using EventHandler = std::function<void(EventArgs*)>;
// Take the function by value, not by pointer.
void RegisterFunction(EventHandler f);
private:
// Store the function by value, not pointer
list<EventHandler>function_list;
};
class two
{
public:
two();
private:
void FunctionEvent(EventArgs* e);
};
two::two()
{
one on;
on.RegisterFunction(std::bind(&two::FunctionEvent, this));
}