1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
|
/// Now let's do it with templates!
// Where T is the parameter, U is the return type.
template <typename U, typename T>
class ButtonTemplate
{
public:
// Pointer to static function with parameters
// T and void*, returning another type U.
typedef U (*pFuncsta)(T, void*);
// Pointer to global function with parameter T
// and return U.
typedef U (*pFuncglb)(T);
ButtonTemplate()
{
callbackfunc_ = NULL;
glbcallbackfunc_ = NULL;
voidptr_ = NULL;
param_ = NULL;
}
void SetCallbackFunc(pFuncsta func, void* ptr, const T& param)
{
glbcallbackfunc_ = NULL;
callbackfunc_ = func;
voidptr_ = ptr;
param_ = param;
}
void SetCallbackFunc(pFuncglb func, const T& param)
{
callbackfunc_ = NULL;
voidptr_ = NULL;
glbcallbackfunc_ = func;
param_ = ¶m;
}
U DoCallback()
{
if (callbackfunc_)
return callbackfunc_(*param_, voidptr_);
else if (glbcallbackfunc_)
return glbcallbackfunc_(*param_);
else
std::cerr << "No callback function set." << std::endl;
}
private:
pFuncsta callbackfunc_;
pFuncglb glbcallbackfunc_;
void* voidptr_;
const T* param_;
};
// Template specialization for a function with void return type.
template <class T>
class ButtonTemplate<void, class T>
{
typedef void (*pFuncsta)(T, void*);
typedef void (*pFuncglb)(T);
public:
ButtonTemplate()
{
callbackfunc_ = NULL;
glbcallbackfunc_ = NULL;
voidptr_ = NULL;
param_ = NULL;
}
void SetCallbackFunc(pFuncsta func, void* ptr, const T& param)
{
glbcallbackfunc_ = NULL;
callbackfunc_ = func;
voidptr_ = ptr;
param_ = ¶m;
}
void SetCallbackFunc(pFuncglb func, const T& param)
{
callbackfunc_ = NULL;
voidptr_ = NULL;
glbcallbackfunc_ = func;
param_ = ¶m;
}
void DoCallback()
{
if (callbackfunc_)
callbackfunc_(*param_, voidptr_);
else if (glbcallbackfunc_)
glbcallbackfunc_(*param_);
else
std::cerr << "No callback function set." << std::endl;
}
private:
pFuncsta callbackfunc_;
pFuncglb glbcallbackfunc_;
void* voidptr_;
const T* param_;
};
|