I am still finding my way around C++ and have encountered a problem. I have a class containing an instance member of another class (can't inherit from), which includes a callback. I would like to register this callback to the parent class but am having difficulty.
After some digging around, I understand method != function, as an instance method implicitly expects an instance of itself (best way I can describe it!) and that std::bind
was an option, but I can't get this to work when the signature is not <void(void)>
.
I also read about implementing as an interface, similar to a delegate (I come from a Swift background), which was also appealing.
Here is a barebones version of what I am trying to achieve:
class ChildClass
{
public:
std::function<int(int)> callback;
};
class MainClass
{
public:
ChildClass childClass;
MainClass()
{
this->childClass.callback = this->square;
}
private:
int square(int i)
{
return i * i;
}
};
I understand mismatching types are causing the error, but I have no idea how I can make them play together.
You can use a lambda (with capturing this
).
MainClass()
{
this->childClass.callback = [this](int i) { return this->square(i); };
}
LIVE
Or if you want to stick to std::bind
:
MainClass()
{
using namespace std::placeholders;
this->childClass.callback = std::bind(&MainClass::square, this, _1);
}
LIVE
And see Bind Vs Lambda? and When should I use std::bind?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With