【问题标题】:How to create EventHandler in c++ linux如何在 C++ linux 中创建 EventHandler
【发布时间】:2019-06-03 21:08:17
【问题描述】:

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

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))' on.RegisterFunction(&FunctionEvent);

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

void FunctionEvent(EventArgs* e)
{

}

int main()
{
    one on;
    on.RegisterFunction(&FunctionEvent);
}

有什么区别?

【问题讨论】:

标签: c++


【解决方案1】:

使这项工作适用于所有情况的最简单和最通用的方法是使用std::function。它真的很容易使用,它就像一个普通的函数一样工作。此外,std::function 可与 lambdas、函数指针一起使用,当与 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));
}

【讨论】:

  • 错误是:没有匹配函数调用'one::RegisterFunction(std::_Bind_helper::type)'
  • 您是否更新了RegisterFunction 的定义,使其接受std::function&lt;void(EventArgs*)&gt;
  • 是的,就像你的例子
  • 您需要为EventArgs* 参数提供一个占位符:std::bind(&amp;two::FunctionEvent, this, std::placeholders::_1)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-02-11
  • 2010-10-15
  • 2014-05-21
  • 1970-01-01
  • 2012-06-26
  • 1970-01-01
相关资源
最近更新 更多