Re: Pointers to member functions are NOT useless
Jonathan Lee <jonathan.lee.975@gmail.com>, on 24/07/2010 08:42:08, wrote:
On Jul 24, 11:10 am, "Francesco S. Carta"<entul...@gmail.com> wrote:
Hi there,
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.
Not to be a Negative Nancy, but I tend to agree with the position that
pointer to member functions are (nearly) useless. I've never used
them.
I'm glad you've been able to find other uses for them, reading the
follow-ups of this thread.
I've never used them either, only today I seriously put myself up for
reasoning on it and I found some usage that I considered useful...
The problem is there seem to be more suitable idioms in most cases.
Take your example. I'd rather use polymorphism and write something
like
void enter(Field f) { current_field = f; }
void move(Movement m) {
switch(current_field) {
case water: return moveWater(m);
case air: return moveAir(m);
case ground: return moveGround(m);
default: throw std::runtime_error("WTField");
}
}
and let the derived classes implement moveXXX(). And
it's not like it's just the example you came up with
that this could be done with. I think you could
refactor this whole category of uses.
....useful in particular to avoid the kind of code you just posted - as I
previously said, in the OP.
You just moved the decision about which function to call from the rarely
used function (the one that sets the context) to the often used function
(the one that should just "do it").
You wasted cycles, and potentially, you heavily slowed down the program:
imagine if there are hundreds or thousands of such objects in a
simulation, would you then try to save as much as possible? I know I would.
--
FSC - http://userscripts.org/scripts/show/59948
http://fscode.altervista.org - http://sardinias.com