如何在 c++ linux 中创建事件处理程序

How to create EventHandler in c++ linux

本文关键字:创建 事件处理 程序 linux c++      更新时间:2023-10-16

我想将自定义事件处理程序创建到一个类中并传递另一个类的函数。

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 (two::( EventArgs(("打开。RegisterFunction(&FunctionEvent(;

如果 FunctionEvent(( 它不属于第二类,就像这样工作:

void FunctionEvent(EventArgs* e)
{
}
int main()
{
    one on;
    on.RegisterFunction(&FunctionEvent);
}

有什么区别?

在所有情况下使其工作的最简单和最通用的方法是使用 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));
}