<ma******@pegasus.cc.ucf.edu> wrote in message
news:11**********************@g49g2000cwa.googlegr oups.com...
// file sltest.h
#ifndef SLTEST_H
#define SLTEST_H
class CallbackBase // herb shutters gotW source ..
{
public:
virtual void operator()() const { };
virtual ~CallbackBase() = 0;
};
CallbackBase::~CallbackBase() { }
template<typename T>
class Callback : public CallbackBase
{
public:
typedef void (T::*F)();
Callback( T& t, F f ) : t_(&t), f_(f) { }
void operator()() const { (t_->*f_)(); }
private:
T* t_;
F f_;
};
template<typename T>
Callback<T> make_callback( T& t, void (T::*f) () )
{
return Callback<T>( t, f );
}
Because the CallbackBase instances are used polymorphically,
the previous function might best be replaced with:
template<class T>
std::auto_ptr<CallbackBase> new_callback( T& t, void(T::*f)() )
{
return std::auto_ptr<CallbackBase>( new Callback<T>(t,f) );
}
class test {
static void callBack() {
// here we'll call the apporpriate fuction
// passed into test.
}
public:
test ()
// : CallBack<>( )
{
}
};
#endif
I'd like to do two things:
1. Retrofit the constructor of the class test to take an object and a
member function. test's initializer list will in turn call the
constructor of CallBack with the parameters passed into test.
2. With test::callBack, call the apporpriate member function that was
passed into the constructor of test. NOTE: The impetus behind this is
predicated upon the use of a vendors API suite, where each call to the
vendors 'doorbellWrite' function (not shown) results in execution of
the member function callBack within test. For greater flexibility I
desire to call my own function from with callBack.
A properly designed callback system should normally provide a "cookie"
(typically a void* pointer) to the callback function.
You would then implement this function with something like:
void test_callback(void* cookie)
{
CallbackBase& cb = *static_cast<CallbackBase*>(cookie);
cb();
}
Encapsulation in a class with RAII could look like:
class Test
{
public:
template<class T>
Test( T& t, void(T::*f)() )
: my_cb( new_callback(t,f) )
{
someAPI_setupCallback( test_callback, my_cb.get() );
//NB: test_callback is the func above - can be static member as well
}
~Test()
{
someAPI_removeCallback( test_callback, my_cb.get() );
}
private:
std::auto_ptr<CallbackBase> my_cb;
//disable copy-assignment and constructor:
Test(Test const&);
Test& operator=(Test const&);
};
Of course in practice, it is a good idea to use boost::function
instead of a custom CallbackBase class...
I hope this helps,
Ivan
--
http://ivan.vecerina.com/contact/?subject=NG_POST <- email contact form
Brainbench MVP for C++ <>
http://www.brainbench.com