I have a class X which has this method:
void setRxHandler(void (*h)(int));
And I want to pass to it a member function that exists in instances of class Y.
void comm_rxHandler(int status);
I tried the following:
x.setRxHandler(comm_rxHandler)
But it get the following compile error (I’m using Qt):
error: no matching function for call to
‘X::setRxHandler(< unresolved overloaded function type>)’
So, how can I do that?
I noticed if I declare comm_rxHandler (class Y) as static, I have no errors. But I want comm_rxHandler as a non-static method. Also I want setRxHandler method (class X) to be generic and not class-specific. So I can’t declare that method as:
setRxHandler(void (Y::*h)(int))
How to do that? Can you help me on this?
Thanks!
As it is now, the
setRxHandlerprototype takes a pointer to a function that doesn’t return anything and takes anint. As you have noticed, this won’t work with member functions because they can’t be called like a normal function (you have to handle thethispointer as well, which means having an instance of that class to call the method on).To make it both work with member functions and non-specific (generic), you have to either make a base class and have all classes you want to use
setRxHandlerwith derive from that class:or use templates:
With the template option, you really have no control over what class will be used with
setRxHandler(excluding RTTI), which can be exactly what you want.