I know this question has been discussed many other times but it seems I can find an answer that I can fully understand.
My Question is how to pass a member function to a second class as a callback in CPP and without using boost library.
I keep encountering Api calls where callback logic is implemented like this. entity.func(MyClass::somemethod, this);
and I'd like to use this kind of notation;
----------------------------DeviceHub Class-------------------------
DeviceHub
instantiates n VirtualDevice
s that requires a DeviceHub
method to be passed as callback so that the VirtualDevice
object can notify the DeviceHub
object.
class DeviceHub{
public:
DeviceHub(int n);
virtual ~DeviceHub();
int virtualDeviceCallback(std::string s);
std::vector<VirtualDevice> virtual_devices;
}
DeviceHub::DeviceHub(int n){
int i;
for(i = 0; i < n; i++){
VirtualDevice vd = VirtualDevice(...,this); //pass callback method and context
virtual_devices.push_back(vd);
}
}
DeviceHub::virtualDeviceCallback(std::string s){
/*do something...*/
}
----------------------------VirtualDevice Class-------------------------
class VirtualDevice{
public:
VirtualDevice(callbackmethod, context);
virtual ~VirtualDevice();
int id;
}
VirtualDevice::VirtualDevice(callbackmethod, context){
//do something
//than fire callback
//context.callbackmethod("some string");
}