5

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.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
Lucas
  • 153
  • 1
  • 11
  • For a member function you need a member function pointer. Since that function doesn't need to be in the class you'd have an easier time if it was a free function. – Retired Ninja May 20 '19 at 00:24
  • 1
    This may help. https://stackoverflow.com/questions/56212392/how-do-i-re-assign-a-function-name-in-c – Retired Ninja May 20 '19 at 00:26
  • You are right, in my original implementation it was a free function, but I had to move it into a member as I would be using the state within (squaring was just as a demo). – Lucas May 21 '19 at 11:47

1 Answers1

4

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?

songyuanyao
  • 169,198
  • 16
  • 310
  • 405