如何使用接口实现回调 [英] How to implement callbacks with interface

查看:133
本文介绍了如何使用接口实现回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个需要更多回调的类。
我试图用一个接口实现它们:

I have a class which needs more callbacks.. I am trying to implement them with an interface:

class CallbacksInterface
{
public:
     virtual bool mycallback1() = 0;
     virtual bool mycallback2() = 0;
     virtual bool mycallback3() = 0;
};

Class BusImplementation{
public:
    addRequest(bool (CallbacksInterface::*callback)());

}

回调是 addRequest()的参数方法,并且被定义为接口方法的指针
所以我想添加请求。

Callback is parameter for addRequest() method and is defined as pointer to interface method. So I want to add request..

//class with callbacks
class Main:CallbacksInterface{
public:
      bool mycallback1(){..};
      bool mycallback2(){..};
      bool mycallback3(){..};
      //.. 
}

BusImplemantation bus;
Main main;   

bus.addRequest(main.mycallback1);          
bus.addRequest(main.mycallback2);
bus.addRequest(main.mycallback3);

但是我无法将回调传递给我的BusImplemantation类

But I cant pass a callback into my BusImplemantation class

error: argument of type 'bool (Main::)()' does not match 'bool (CallbacksInterface::*)()'

我认为有一个带有模板的解决方案,但是我正在对嵌入式设备进行编程,并且我的编译器很有限。

I think there is a solution with templates, but I am programming embedded devices and my compiler is limited.

推荐答案

一种简单的方法是定义表示函数的单个接口类型:

A simpler approach would be to define a single interface type representing a function:

struct ICallback
{
  virtual bool operator()() const = 0;
};

并根据需要实施多次:

struct Foo : ICallback
{
  virtual bool operator()() const { return true;}
};

struct Bar : ICallback
{
  virtual bool operator()() const { return false;}
};

然后您的总线实现可以使用回调接口:

then your bus implementation can take callback interfaces:

class BusImplemantation{
public:
    void addRequest(const ICallback* callback) { .... }
};

然后

BusImplemantation bus;
Foo foo;  // can be called: bool b = foo();
Bar bar;   // can be called: bool b = bar();

bus.addRequest(&foo);          
bus.addRequest(&bar);

您也可以使用 std :: function 并完全避免使用通用界面。

You could also investigate using std::function and avoiding the common interface altogether.

这篇关于如何使用接口实现回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆