I'm fairly new to the concept of function pointer in C++, so I don't know how to write my question properly. Please bear with me.
Basically, what I'm trying to do is to create a Button object whose constructor accepts a function pointer as its parameter. That function pointer points to a function which will change state of the StateMachine.
Here is the sample code (it doesn't work, and irrelevant bits have been stripped out)
Button.h
#include "StateMachine.h"
class Button
{
private:
void (*m_onclickAction)(); //a data member
public:
Button(void (*action)());
};
StateMachine.h (I didn't write it, I just use it with permission. So there should be no problem with the code, and I don't want to modify it)
#include <map>
template<class E, class T>
class StateMachine
{
public:
typedef void (T::*CallbackOnInitialise)();
typedef void (T::*CallbackOnExit)();
private:
T* m_pOwner;
E m_currentState;
// Maps to store function pointers to state functions.
std::map<E, CallbackOnInitialise> m_statesOnInitialise;
std::map<E, CallbackOnExit> m_statesOnExit;
public:
StateMachine(T* pOwner, E emptyState)
{
m_currentState = emptyState;
m_pOwner = pOwner;
}
void ChangeState(E statenext)
{
//do something to change the state
}
};
So that in my main Program class, I could be able to do something like this
#include "Button.h"
#include "StateMachine.h"
//Code to instantiate an StateMachine object goes here
Button* aButton = new Button(aStateMachine->ChangeState(NEW_STATE));
The problem is I can't think of a way to correctly pass the NEW_STATE, which is an enum declared in the Program class as the function pointer is expecting no parameter. I have tried tweaking around with it, but no success.
Any suggestion on how should I do it?