Created
February 8, 2012 06:39
-
-
Save AndreLouisCaron/1766094 to your computer and use it in GitHub Desktop.
Callback
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <Windows.h> | |
namespace w32 { namespace tp { | |
class Hints; | |
class Queue; | |
// Dispatches calls to a function with a painful signature (see PTP_TIMER). | |
class Timer | |
{ | |
/* class methods. */ | |
private: | |
// allocate timer handle and register callback. | |
static ::PTP_TIMER setup ( | |
::PTP_CALLBACK_ENVIRON queue, | |
::PTP_TIMER_CALLBACK callback, | |
void * context | |
); | |
/* nested types. */ | |
public: | |
// compile-time binding for free function. | |
template<void(*F)(Hints&,void*)> struct function; | |
// compile-time binding for member function. | |
template<typename T, void(T::*M)(Hints&)> struct method; | |
/* data. */ | |
private: | |
::PTP_TIMER myHandle; | |
/* constructors. */ | |
public: | |
template<void(*F)(Hints&,void*)> | |
Timer ( Queue& queue, function<F> function, void * context=0 ) | |
: myHandle(setup(queue.handle(), function, context)) | |
{ | |
} | |
template<typename T, void(T::*M)(Hints&)> | |
Timer ( Queue& queue, T& object, method<T,M> method ) | |
: myHandle(setup(queue.handle(), method, &object)) | |
{ | |
} | |
// ... | |
}; | |
template<void(*F)(Hints&,void*)> | |
struct Timer::function | |
{ | |
// Return function with the proper signature that | |
// invokes the free function bound at compile-time. | |
operator ::PTP_TIMER_CALLBACK () const | |
{ | |
return (&timer_callback); | |
} | |
private: | |
static void __stdcall timer_callback( | |
::PTP_CALLBACK_INSTANCE instance, | |
void * context, | |
::PTP_TIMER handle | |
) | |
{ | |
F(Hints(instance), context); | |
} | |
}; | |
template<typename T, void(T::*M)(Hints&)> | |
struct Timer::method | |
{ | |
// Return function with the proper signature that | |
// casts the context pointer to 'T*' and invokes | |
// the member function bound at compile-time. | |
operator ::PTP_TIMER_CALLBACK () const | |
{ | |
return (&timer_callback); | |
} | |
private: | |
static void __stdcall timer_callback( | |
::PTP_CALLBACK_INSTANCE instance, | |
void * context, | |
::PTP_TIMER handle | |
) | |
{ | |
(static_cast<T*>(context)->*M)(Hints(instance)); | |
} | |
}; | |
} } | |
// ... USE AS FOLLOWS: | |
class Foo | |
{ | |
public: | |
void bar ( w32::tp::Hints& ); | |
}; | |
using w32::tp::Timer; | |
Timer timer(queue, foo, Timer::method<Foo,&Foo::bar>()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment