Original Post
Greetings, I'm using a GUI program to help me expand upon my C++ knowledge when I came across the issue of linking a Button to some function. I wanted to be able to link a wide variety of functions to any Button on the fly and came up with this. My question is, are there any pitfalls from this method? This currently limits me to only functions that return nothing and take no parameters, but that works for now so I'll address that at a later time. Comments?
// Function Pointer wrapper
class FunctionPointer
{
public:
virtual void Call() {}
};
template <typename T>
class FunctionPointerTemplate : public FunctionPointer
{
public:
FunctionPointerTemplate(T* object, void (T::*member_function)())
{ pObject = object; pMemberFunction = member_function; }
void Call()
{ (pObject->*(pMemberFunction))(); }
private:
T* pObject;
void (T::*pMemberFunction)();
};
// Button class member function, called upon to link a function to the button action.
template <typename T>
void LinkFunction(T* object, void (T::*member_function)())
{
if (m_pFunction != NULL) // m_pFunction is initialized to NULL in constructor
{ delete m_pFunction; }
FunctionPointerTemplate<T>* function = new FunctionPointerTemplate<T>(object, member_function);
m_pFunction = function;
}
// Linking a function (the 'Apply' function of a dialog window) to the Button
pButton->LinkFunction(pDialogWindow, &DialogWindow::Apply);