Re: Pointers to member functions are NOT useless
On 07/25/10 11:57 AM, Francesco S. Carta wrote:
Jonathan Lee <jonathan.lee.975@gmail.com>, on 24/07/2010 08:42:08, wrote:
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.
There's probably a template solution as well if opening up the code to
optimisation is important. That's the thing about C++, there are
invariably many ways to skin a particular cat. Of all the possible
options, function pointers are the least friendly to the optimiser.
Function pointers are more commonly used in C and C++ mainly because C
only has a single skinning technique.
--
Ian Collins