I'm making a game engine. But i have a little problem.
I have a CONTROL class which controls keyboard settings.
class CONTROL
{
struct key
{
string name;
short key;
void (*keyEvent)(void);
}
public:
SetKey(string name, short key);
OnKeyPress(string name, void(*event)(void) );
};
I want to pass any function to OnKeyPress function.
In my other(user of the engine can set an other name for this class. ) class:
class OTHER
{
void Forward();
CONTROL *control;
public:
void Other()
{
control->SetKey("forward",VK_KEY_W);
control->OnKeyPress("forward", &this->Forward);
}
int AnotherFunction()
{
control->Run();//it runs all keyboard events.
return 1;
}
};
But i get an error.
So, how can i do it?
Pointers to static functions and methods are different. In a way method is a static function with one additional parameter (the object which is calling it). A pointer that could point to Forward is "void (OTHER::*ptr)()", I think.
I guess the most flexible solution would be to write an abstract class Action with a virtual method exec(), derive a class StaticFunctionAction from it, containing a pointer to a static function and with exec() implemented to call that function, and a class OTHER_MethodAction, containing a pointer to OTHER object and a pointer to it's method with exec() which does (other_ptr->*method_ptr)(). CONTROL would have a pointer to an Action instead of keyEvent. That way you could use the same control class to call any kind of functions.