In a non-boost project, I have a class which uses a timer based on a certain user action (button pressed/released). I want this class generic, so it takes callbacks for user defined actions.
// TimerClass.h
typedef void (*timerCallback)(void);
...
Class TimerClass : public CButton {
public:
void setCallbackShortTime(timerCallback clickFn) { shortCallback = clickFn;} ;
void setCallbackLongTime(timerCallback clickFn) { longCallback = clickFn;} ;
private:
timerCallback shortCallback, longCallback;
}
// CMyDlg.h
class CMyDlg : public CDialog
{
public:
void openLiveViewWindow();
void openAdminPanelWindow();
TimerClass _buttonSettings;
}
// CMyDlg.cpp
...
_buttonSettings.setCallbackShortTime(&openLiveViewWindow);
...
Now, from another class (DialogClass) I can use the TimerClass but I cannot pass function pointers to the callback functions. These functions are not static. The compiler ends up complaining:
error C2276: '&' : illegal operation on bound member function expression
Some research on this pointed out to std::function() and std::bind() but I'm not familiar with these and would appreciate some pointers on how to resolve this.
RESOLUTION: For anyone interested, here are the bricks of the final solution
// TimedButton.h
#include <functional>
// define timer callback prototype
typedef std::function<void()> timerCallback;
...
class TimedButton : public CButton
{
public:
TimedButton();
...
void setCallbackShortTime(timerCallback clickFn) { _shortCallback = clickFn;} ;
void setCallbackLongTime(timerCallback clickFn) { _longCallback = clickFn;} ;
private:
timerCallback _shortCallback;
timerCallback _longCallback;
}
// TimedButton.cpp
...
(_longCallback)(); // call long duration fn
...
(_shortCallback)(); // call short duration fn
// in MyDlg.cpp
#include <functional>
...
_buttonSettings.setCallbackShortTime(std::bind(&CMyDlg::openLiveViewWindow, this));
_buttonSettings.setCallbackLongTime(std::bind(&CMyDlg::openAdminPanelWindow, this));