In a project without promotion, I have a class that uses a timer based on a specific user action (the button is pressed / released). I want this class to be generic, so it accepts callbacks for user-defined actions.
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;
}
class CMyDlg : public CDialog
{
public:
void openLiveViewWindow();
void openAdminPanelWindow();
TimerClass _buttonSettings;
}
...
_buttonSettings.setCallbackShortTime(&openLiveViewWindow);
...
Now from another class (DialogClass) I can use TimerClass, but I can not pass pointers to callback functions. These functions are not static. The compiler complains:
error C2276: '&' : illegal operation on bound member function expression
In some studies, this pointed to std::function()and std::bind(), but I am not familiar with them and would like to evaluate some ways to solve this problem.
PERMISSION . For anyone interested, here are the bricks of the final decision
#include <functional>
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;
}
...
(_longCallback)();
...
(_shortCallback)();
#include <functional>
...
_buttonSettings.setCallbackShortTime(std::bind(&CMyDlg::openLiveViewWindow, this));
_buttonSettings.setCallbackLongTime(std::bind(&CMyDlg::openAdminPanelWindow, this));