1

I need to call a function when a button is pressed. The following function should take in the function to be called:

void ButtonLayer::LoadButton(void(*func)()) {
     // do button loading stuff
     // if button is clicked...
     func();
}

This would work except for the fact that passing a function within a seperate namespace gives the following error:

argument of type "void(OtherLayer::*)()" is incompatiable with parameter of type "void(*)()"

I don't want to make every function I pass static to avoid this problem, so I need some way of converting a function within a namespace to be of type void(*). I have tried static casting but I'm unsure of the exact syntax as I'm new to C++

  • 1
    Is `OtherLayer` a class? Member functions are not convertible to function pointers. – Yksisarvinen Apr 07 '20 at 08:11
  • OtherLayer is a class, but in my actual code I have it inside a System:: namespace, so it could be System::OtherLayer::* and the problem still applies – Spencer Deane Apr 07 '20 at 08:13
  • 5
    Namespaces doesn't matter. You cannot use non-static class member function as function pointer, because they are of different types. If you can change `LoadButton` to take `std::function` argument, it will be possible to pass member function there, or you have to workaround it somehow. – Yksisarvinen Apr 07 '20 at 08:15
  • I will look into std::function, thankyou – Spencer Deane Apr 07 '20 at 08:19
  • You may want to pass a lambda that captures the `OtherLayer` object if you don't want or can to change the interface of `LoadButton`. – bitmask Apr 07 '20 at 08:29
  • Agree with Yksisarvinen. For a callback like this, `std::function` can work, although you might want to consider `std::function`. This second form allows you to share a single callback between multiple buttons. Furthermore, you'll probably will want a lambda like `[this](Button& b){this->func(b); }` – MSalters Apr 07 '20 at 08:29
  • Does this answer your question? https://stackoverflow.com/questions/400257/how-can-i-pass-a-class-member-function-as-a-callback Perhaps you need to scroll a bit down to find an answer that applies in your case – 463035818_is_not_an_ai Apr 07 '20 at 08:43

2 Answers2

0

It seems that you want to pass a member function.

This example may help you.

class A {
public:
    int i;
    int fun(int j) {
        return i + j;
    };
};
void fun(int j, A ob, int (A::* p)(int)) {
    std::cout << (ob.*p)(j);
}
void main() {
    int (A:: * fp)(int);    //declare fp as a function pointer in class A
    fp = &A::fun;          //init fp
    A obj;
    obj.i = 1;
    fun(123, obj, fp);
}
songyuanyao
  • 169,198
  • 16
  • 310
  • 405
victor12369
  • 143
  • 10
0

Based on @Yksisarvinen and @MSalters comments, the solution was:

void ButtonLayer::LoadButton(std::function<void()>) {
     // do button loading stuff
     // if button is clicked...
     func();
}

and then to call it:

LoadButton([this] { functionToCall; });