Re: Pointers to member functions are NOT useless
On Jul 24, 4:10 pm, "Francesco S. Carta" <entul...@gmail.com> wrote:
after reading an article complaining that pointers to member
functions are misconceived in C++, and after reading a comment
about them saying that they happen to be a rarely necessary
feature - if ever necessary at all - I decided to investigate
them to see how I could take advantage of them, and I also
decided to post this message to get the group's feedback.
A pointer to member function is a pointer that can memorize
the displacement of any member function so that we can call
that function on an appropriate object without having to know
which function we are calling in particular - though, the
object and the member function must belong to the same class
(please forgive me if this description is oversimplified, but
also please correct me if it happens to be wrong).
They don't have to belong to the same class, although the
classes do have to be related by inheritance.
And there's no real "offset" involved. There are two common
techniques for implementing them: in the most obvious, the
pointer stores either the actual address of the function (if
non-virtual) or the index into the vtable (if virtual), some
means of distinguishing between the two, and any correction
necessary to the this pointer. Alternatively, the compiler
generates a trampoline function, which does whatever is
necessary, and stores a pointer to it.
I've come to think that this feature can be really useful if
we have objects that can perform different actions in case
they are used in a context or another.
The approach to take (having not pointers to member functions at our
disposal) would be to use a switch or some ifs any time we have to
perform the action, so that we can choose the right function for the
current context or input.
If we happen to have several operations to perform, but the context /
input rarely changes, having to decide which action to perform at each
call is a waste of cycles.
With pointers to member functions we can store our decision about which
member function to call and speed up the whole process.
A more frequent approach to this problem involves using an
instance of a forwarding class.
The most frequent use of pointers to member functions is in
instantiating templates, where the pointer to member function is
in fact resolved at compile time.
Since I'm biased towards interfaces and games, the example I
post here below is just a stub of a game where we have a
common interface for several different moving objects - I
think the approach I've taken in that example could lead to a
nice infrastructure where different objects must interact (or
refuse to interact) with different environments.
Some early GUI frameworks made extensive use of them for
callbacks.
--
James Kanze