Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement callbacks with interface

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.

like image 768
Meloun Avatar asked Dec 05 '25 08:12

Meloun


1 Answers

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.

like image 102
juanchopanza Avatar answered Dec 07 '25 21:12

juanchopanza



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!