Re: Function pointer and functor problem
In article
<2c8fe4e0-b573-48c3-aeee-b4a79fa03978@u57g2000hsf.googlegroups.com>,
"lali.cpp" <lali.cpp@gmail.com> wrote:
So the queue would be like:
typedef void (*ptr)( );
queue<ptr> timer_queue;
Take a look at boost::function and boost::bind, as in:
typedef boost::function<void()> ptr;
queue<ptr> timer_queue;
Timer timer;
A obj_of_a;
B obj_of b
// please remember that timer uses a queue of function pointers
timer.registerTimer(A::timerExpired,6)// expires after 5 seconds
timer.registerTimer(B::timerExpired,2) // expires after 2 seconds
You would write this as:
timer.registerTimer(boost::bind(&A::timerExpired, &obj_of_a), 6);
timer.registerTimer(boost::bind(&B::timerExpired, &obj_of_b), 2);
Can it be done somehow using wrapper static functions of classes A and
B ??
It can be. For each entry in your timer_queue, an additional void*
pointer has to be kept that is passed to the callback.
typedef void (*Fn)();
struct ptr
{
Fn fn;
void* p;
}
queue<ptr> timer_queue;
Your classes would look like:
class A
{
void doTheWork() { /* ... */ }
public:
static void timerExpired(void* ptr)
{ static_cast<A*>(ptr)->doTheWork() ; }
};
and registering would look like:
timer.registerTimer(&A::timerExpired, &obj_of_a, 6);
Unless you have measurable performance concerns, function and bind is
definitely the way to go.
1. It both less work for clients of timer to use
2. It is more flexible because can take either a function or a function
object that has the correct signature.
--
Nevin ":-)" Liber <mailto:nevin@eviloverlord.com> 773 961-1620
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]