Re: Member functions as Callback functions
On Dec 22, 3:55 pm, Andre Kaufmann <akfmn...@t-online.de> wrote:
I wished callbacks would be supported directly by the C++ compiler. ...
The more I've worked on trying to find a "better" callback
mechanism for my code, the more I think that C++ falls
down in this regard. _None_ of the C++-ish methods is
as straightforward as the C-style method, and most are
less efficient. The main disadvantage of the C-style
method is that it is "not type-safe," but my experience
is that this is not much of a problem. Boost "bind"
does allow you to change the argument list around, but
I've never run into a need for this. (Maybe other people
have.)
What is needed, IMHO, is a way to automatically pass an
object pointer and a pointer to a member function,
so that the member function may be called with the
object pointer as "this", without the function doing
the callback knowing anything about the object.
For most implementations, this could be done with a
2-member structure containing:
1. A pointer to the object, already cast (adjusted)
to the appropriate type. "void *" does _not_
work here, because the Standard requires
that "void *" be basically a pointer to an
unsigned char array containing the object.
This doesn't work if the correctly typed
pointer points somewhere in the middle of
the object (e.g., with multiple inheritance.)
2. A pointer to the member function, regarded as
a function with an additional parameter for the
"this" pointer. The type of the object pointer
would be whatever this function expects.
Note that "proof of concept" (and C-front?)
implementation of member functions is already
set up this way.
The function doing the callback could then just
call the member function, using the object
pointer "as is". The compiler can guarrantee
that the type of the pointer and the type of the
function are compatible.
Doing it this way would be about as fast as you
can do it, and would place no constraints on the
callback function, aside from the return value
and (normal) arguments, which you can't avoid.
I have no particular suggestions for syntax,
except that maybe the callback could be passed as
"obj->function" or "&(obj->function)"
I also have no idea if there's much support for
putting something like this into the Standard.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]