0

I started using C++ recently and at one point I needed to set up a callback, i.e. call a function of another class and pass to it as a parameter the name of one of my own functions so that it calls it back. At first I tried this:

void myOtherFunction(void (*oneOfMyFunctions)(void)) {
    oneOfMyFunctions();
}

Unfortunately this code doesn't support class member functions because it is (correct me if I am wrong) ...C code.

Th0rgal
  • 703
  • 8
  • 27

2 Answers2

1

This can work.

void myOtherFunction(void (*oneOfMyFunctions)(void)) {
    oneOfMyFunctions();
}

However, your problem may be due to trying to pass member functions into this function. If member_function is a member function of class A, the expression &member_function inside class A has a type of void (A::*)(void), not void (*)(void) like you want (that is, it wants an A pointer in addition to its normal parameters). You can use std::bind():

std::bind(&member_function, this)

to create a function object which can be called with an empty parameter list. However, then you would need to change your member function signature to something like this:

template <typename FuncType>
void myOtherFunction(FuncType oneOfMyFunctions) {
    oneOfMyFunctions();
}

or, like Th0rgal may have said,

void myOtherFunction(std::function<void()> oneOfMyFunctions) {
    oneOfMyFunctions();
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Anonymous1847
  • 2,568
  • 10
  • 16
0

Here is a working way to do that:

void myOtherFunction(std::function<void()> oneOfMyFunctions) {
    oneOfMyFunctions();
}

And inside my class:

myOtherFunction([&] {
    oneOfMyFunctions();
});

Some explanations: In std::function<void()>, void is what is returned by the function and () contains the types of its parameters (mine is empty because it doesn't have any).

In the 2nd code I am using a lambda to keep the context, as a bind would do (but lambdas replace them).

Th0rgal
  • 703
  • 8
  • 27