Re: Avoiding pointers to member functions
On Jan 30, 7:00 pm, Robert Fendt <rob...@fendt.net> wrote:
I am trying to find the best way to make part of a class's
behaviour configurable during runtime, yet with as little
overhead as possible. Maybe someone here has an idea? So far I
have come up with 3 alternatives, all of which I do not really
like for different reasons.
(1) The 'simple' solution would be to implement various
alternatives of the (private) member function in question, and
use a "pointer to member function" to access it. Runtime
configuration can be achieved by changing the pointer value,
and a function pointer should be at least as efficient as a
single vtable lookup. However, I loathe function pointer
syntax, and they are clumsy to use (and they IMHO hide
semantics by their convoluted syntax).
Also, they tend to be much less efficient than calling a virtual
But the real arguments against them are those you raised, along
with the fact that you cannot associate data with them. (You
don't say what sort of configuration you're dealing with, but
it's easy to imagine configurations with parameters, e.g.
scaling or translations.)
(2) So, what about a functor class. It would have to be a
member or friend of the outer class, and it cannot directly
access the latters internals (even with 'friend' I would still
have to give it a pointer to the current instance). I am also
concerned about performance, since there is an additional
level of indirection involved at several points when using
I doubt that the performance issues will be relevant. It's a
(3) Last but not least: strict OO design, make a base class
and several differently behaving child classes, and use a
factory pattern to achieve at least some level of runtime
flexibility. This is less flexible, so I do not really like
that possibility either. Also there is the risk of duplicate
I'm not too sure where you see the code duplication; the derived
class can always call functions in the base class for common
What you describe is basically the template method pattern. It
has the drawback that you can't change the configuration once
the class has been instantiated.
So, would someone please tell which obvious clear, flexible
and efficient solution I am missing?
It sounds to me that you're looking for the strategy pattern,
but it's hard to say without more details.