#include<windows.h>
#include<map>
class callback_t {
public:
virtual void invoke() = 0;
};
template<class T>
class callback0 : public callback_t {
typedef void (T::*func_t)();
T* cls_;
func_t func_;
public:
void attach(T* cls, func_t func)
{ cls_ = cls; func_ = func; }
void invoke()
{ (cls_->*func_)(); }
};
template<class T, typename P1>
class callback1 : public callback_t {
typedef void (T::*func_t)(P1);
T* cls_;
func_t func_;
P1 p1_;
public:
void attach(T* cls, func_t func, P1 p1)
{ cls_ = cls; func_ = func; p1_ = p1; }
void invoke()
{ (cls_->*func_)(p1_); }
};
typedef std::map<UINT_PTR, callback_t*> timer_map_t;
static timer_map_t g_timer_map;
static void CALLBACK TimerProc(HWND hwnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTime)
{
timer_map_t::const_iterator it = g_timer_map.find(idEvent);
if (it == g_timer_map.end()) return;
callback_t* cb = it->second;
if (cb == NULL) return;
cb->invoke();
}
UINT_PTR ex_set_timer(UINT_PTR id, unsigned int period, callback_t* cb)
{
UINT_PTR new_id = SetTimer(NULL, id, period, TimerProc);
g_timer_map[new_id] = cb;
return new_id;
}
bool ex_kill_timer(UINT_PTR idEvent)
{
timer_map_t::const_iterator it = g_timer_map.find(idEvent);
if (it == g_timer_map.end()) return false;
g_timer_map.erase(it);
return true;
}
//
// пример
//
class MyClass {
callback1<MyClass, int> cb_;
UINT_PTR timer_;
public:
void init() {
cb_.attach(this, &MyClass::on_timer, 10);
timer_ = ex_set_timer(0, 0, &cb_);
}
void destroy() {
ex_kill_timer( timer_ );
}
void on_timer(int tag) {};
};
void main()
{
MyClass obj1;
obj1.init();
//MessagePump();
}