I have an issue that I'm not sure how to get around.
I am using a library whose instances of the class are constructed by being passed references to a few functions.
void func_on_enter() {...}
void func() {...}
void func_on_exit(){...}
State state_a(&func_on_enter, &func, &func_on_exit);
I am writing a class that contains an instance of this class, and as such have attempted something like this:
class MyClass{
private:
void func_on_enter() {...}
void func() {...}
void func_on_exit(){...}
State _state_a;
public:
MyClass() : _state_a(&func_on_enter, &func, &func_on_exit) {}
};
I get the error "ISO C++ forbids taking the address of an unqualified or parenthesized non-static member function to form a pointer to member function. Say '&MyClass::_func_on_enter'" (and the same for the other two methods obviously). The compiler helpfully provides a solution, which I tried.
However the compiler then reminds me that there is no matching function for a call to 'State::State(void (MyClass::*)(), void (MyClass::*)(), (MyClass::*)())'
and that it has no known conversion from 'void (MyClass::*)()'
to 'void(*)()'
.
I tried reading up on similar questions about this error but can't seem to find a solution that I both understand and can help in this situation.
I considered trying to add an overload constructor to State, but this seems absurd to do on a class by class case, considering that I could be calling it from any other class.
I also thought for a while that I could just make the functions static (as they're the same for all instances of MyClass), but I quickly remembered that they would then be unable to use non-static member variables of MyClass.
Is there perhaps a way that I can provide a conversion or provide the pointers for the State constructor in another way?
I could really do with some help on this, as I'm quite stuck for ideas on how to move forward. Any help or hints would be greatly appreciated!
State
class? If you are, switch from rawvoid(*)()
pointers tostd::function<void()>
or templateState
on the type of the callbacks. If you're not, what you want may be difficult to impossible.func
etc static.std::function<void()>
. I'm not very familiar withstd::function
, am I understanding correctly that they can be used similarly to pointers to indirectly call a function? If so, I can see this being the solution!