2

I have a similar situation:

class A {
    void callingFunction() {
      calledFunction(passedFunction);
    }

    void calledFunction(std::function<void(int)> foo) {
    }

    void passedFunction(int arguments) {
    }
};

The compiler error is

error: invalid use of non-static member function

How do I achieve this without making the passedFunction static?

Doing this:

calledFunction(std::bind(&A::passedFunction, this);

Creates this error:

error:static assertion failed: Wrong number of arguments foor pointer-to-member

Does it mean I have to provide all the arguments in the callingFunctionwhen passing the passedFunction? This is not possible as the arguments for the passedFunction are specified in the calledFunction

skluzada
  • 153
  • 12

1 Answers1

1

You can write a lambda capturing this, on which passedFunction could be called.

calledFunction([this](int v) { this->passedFunction(v); });
songyuanyao
  • 169,198
  • 16
  • 310
  • 405
  • 1
    Yes, but note that depending on what you do with the `std::function`, it's possible to get a `std::function` containing the `A*` pointer which was captured as `this` to live past the lifetime of the `A` object, so be careful about lifetimes. – aschepler May 21 '18 at 12:40
  • This works thank you. – skluzada May 21 '18 at 12:56