"Fred Baxter" <df*****@fieieied.com> wrote...
"Victor Bazarov" <v.********@comAcast.net> wrote in message
news:WK*******************@newsread1.mlpsca01.us.t o.verio.net... Fred Baxter wrote:
It is possible (and not very difficult) to rewrite your code snippet to
use pointers to non-static members of 'A'. Essentially the same result
is achieved.
What don't you like about this way that makes you to look for "better"?
It just seems a bit inelegant to be passing pointers to isntances to be
used in static functions. How would you re-write the code to use pointer
to non-static member? That would seem more robust, if it encapsulated the
registered class instance as well as its member function.
A pointer to member will *not* eliminate the necessity to pass a pointer or
a reference to the instance. Of course, if you use a reference you need to
initialise it and you'll never get the second chance, with a pointer you
can change it later on.
class CallMeBack {
public:
void foo(int);
void bar(int);
};
class WillCallBack {
void (CallMeBack::*cb)(int);
CallMeBack *pcb;
public:
WillCallBack(CallMeBack *p, void (CallMeBack::*f)(int))
: pcb(p), cb(f) {}
void doit(int i) { (ocb->*cb)(i); }
void change_cb(void (CallMeBack::*f)(int)) { cb = f; }
void change_ptr(CallMeBack *p) { pcb = p; }
};
int main()
{
CallMeBack waiting;
WillCallBack promise(&waiting, &CallMeBack::foo);
promise.doit(42);
promise.change_ptr(&CallMeBack::bar);
promise.doit(42);
CallMeBack another;
promise.change_ptr(&another);
promise.doit(42);
}
Victor