home *** CD-ROM | disk | FTP | other *** search
- Xref: sparky comp.lang.c++:20105 comp.std.c++:2148
- Newsgroups: comp.lang.c++,comp.std.c++
- From: nikki@trmphrst.demon.co.uk (Nikki Locke)
- Path: sparky!uunet!spool.mu.edu!agate!doc.ic.ac.uk!pipex!ibmpcug!demon!trmphrst.demon.co.uk!nikki
- Subject: Re: Callbacks -- suggested approaches??
- Reply-To: nikki@trmphrst.demon.co.uk
- References: <DAVIDM.93Jan25171343@consilium.com>
- Distribution: world
- Followup-To: comp.lang.c++
- X-Mailer: cppnews $Revision: 1.31 $
- Organization: Trumphurst Ltd.
- Lines: 77
- Date: Thu, 28 Jan 1993 13:27:12 +0000
- Message-ID: <728252832snx@trmphrst.demon.co.uk>
- Sender: usenet@demon.co.uk
-
- In article <DAVIDM.93Jan25171343@consilium.com> davidm@consilium.com (David S. Masterson) writes:
- > I'm looking for suggestions on how to handle callback functions in C++ that
- > will be more standard than the one we're currently using.
- ..
- > typedef void (Process::*Method)(Message*);
- > struct Callback {
- > Method method
- > Process* methodthis; // could be multi-threaded
- > } table[MAXCALLBACKS];
- >
- > Methods would be dispatched like:
- >
- > void Process::Dispatch(Message* m) {
- > return (table[Lookup(m)].methodthis->*
- > table[Lookup(m)].method)(m);
- > }
- >
- > The registration method for callbacks looks like:
- >
- > void Process::Register(Method m, Process* p) {
- > table[i].method = m;
- > table[i].methodthis = p;
- > }
- >
- > and is called like:
- >
- > mainproc->Register((Method) MYProcess::callback1, myproc);
- >
-
- Personally, I use templates (or generics) for this sort of thing.
- Something like ...
-
- class CallbackBase
- {
- public:
- virtual void despatch(Message *m) = 0;
- virtual ~CallbackBase() {} // Just in case someone creates
- // a new kind of Callback which needs a destructor
- };
-
- template <class X> class Callback : public CallbackBase
- {
- void (X::*method)(Message *);
- X& methodthis;
- public:
- Callback(void (X::*m)(Message *), X& t) : method(m), methodthis(t) {}
- void despatch(Message *m) { (methodthis->*method)(m); }
- };
-
- Your table is of CallbackBase pointers.
-
- Methods would be dispatched like:
-
- void Process::Dispatch(Message* m)
- {
- table[Lookup(m)]->despatch(m);
- }
-
- The registration method for callbacks looks like:
-
- void Process::Register(CallbackBase *p)
- {
- table[i].callback = p;
- }
-
- and may be called like:
-
- mainproc->Register(new Callback<MYProcess>(MYProcess::callback1, myproc));
-
- You do have to take care of deleting the CallbackBase items, but that can
- probably be done in the Process destructor.
-
- [Note - code not compiled or tested, but I do use something very similar.]
-
- --
- Nikki Locke,Trumphurst Ltd.(PC and Unix consultancy) nikki@trmphrst.demon.co.uk
- trmphrst.demon.co.uk is NOT affiliated with ANY other sites at demon.co.uk.
-