How to implement callbacks with interface

北城以北 提交于 2019-12-10 10:32:40

问题


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)());

}

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);

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.


回答1:


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

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

and implement it as many times as necessary:

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) { .... }
};

then

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

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

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




回答2:


I also strongly suggest going with an abstract interface. However, if you really want the original approach for some reason, you need something like this:

void addRequest(bool (CallbacksInterface::*callback)(), CallbacksInterface* pTarget) {...}
...
bus.addRequest(&CallbacksInterface::mycallback1, &main); 
// ! Not &Main::mycallback1 - that wouldn't compile
...
// calling a callback
(pTarget->*callback)();


来源:https://stackoverflow.com/questions/12387740/how-to-implement-callbacks-with-interface

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!