I have a function that needs to call a virtual method many times in a loop and was hoping there would be a way to avoid the overhead of a vtable lookup every time. I thought maybe obtaining a pointer to the method would be a good way round this. The code below shows what I’m trying to do, the problem being that the address of a method in Derived cannot be assigned to a Base member function pointer.
class Base
{
public:
typedef float ( Base::*MFP )( float const & x ) const;
virtual MFP getMFP( void ) const = 0;
virtual float function( float const & x ) const = 0;
};
class Derived : public Base
{
public:
virtual MFP getMFP( void ) const
{
return &Derived::function;
}
virtual float function( float const & x ) const
{
return x * x;
}
};
class Other
{
public:
float calculate( float const & x, Base * pBase ) const
{
Base::MFP function = pBase->getMFP();
return ( ( *pBase ).*( function ) )( x );
}
};
Is there a way to do what I’m trying to do here?
EDIT:
For anyone who’s still interested I ran a timed test of my code. Turns out dynamic dispatch only slowed down my calculation method by 0.004%, so pretty much nothing. Compiled using MSVC 2010 with full optimisation.
Don’t do it. The processor has deep pipelines, and the compiler is almost certainly already caching the function pointer. You can do this with some effort. But I guarantee that on any compiler less than 10 years old this will make no difference.