Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

c++ callbacks to another member function

I have a question on callbacks. Previously, I am associating my callbacks to a class Q

class Q{
   using Callback = std::function<void(char*, int)>;
   Q:Q();
   Q:~Q();

   void Q::RegisterCB(Callback callbackfunc)
   {
       callback_func = callbackfunc;
   }

   void Q:someEvent()
   {
      callback_func();
   }
};

void handleCallback( char*, int)
{
   // perform some routine

}

// from my main file
int main()
{
   Q q;
   q.RegisterCB(&handleCallback);

}

It works well for me. However, when I need to transfer the handleCallback function to another class for cleaner code. I have problem with using same code

class R{

   void R::handleCallback( char*, int)
   {
   // perform some routine

   }

   void R::someOp()
   {
       // q is some member variables of R
       q.RegisterCB(&R::handleCallback, this);

   }

};

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

However, i run into some problems of saying there is a "no matching function for call to …..". I thought it was just simply assigning from function name to class function name

May I have a hint to where I might go wrong?

Regards

>Solution :

&R::handleCallback has the type void (R::*)(char*, int), which is not convertible to std::function<void(char*, int)>.
Also, RegisterCB takes one argument, not two.

The most straightforward fix is to wrap the call in a lambda function,

q.RegisterCB([this](char* p, int x) { handleCallback(p, x); }); 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading