I have a situation in which I want a member function pointer to a virtual function that avoids dynamic dispatch. See below:
struct Base
{
virtual int Foo() { return -1; }
};
struct Derived : public Base
{
virtual int Foo() { return -2; }
};
int main()
{
Base *x = new Derived;
// Dynamic dispatch goes to most derived class' implementation
std::cout << x->Foo() << std::endl; // Outputs -2
// Or I can force calling of the base-class implementation:
std::cout << x->Base::Foo() << std::endl; // Outputs -1
// Through a Base function pointer, I also get dynamic dispatch
// (which ordinarily I would want)
int (Base::*fooPtr)() = &Base::Foo;
std::cout << (x->*fooPtr)() << std::endl; // Outputs -2
// Can I force the calling of the base-class implementation
// through a member function pointer?
// ...magic foo here...?
return 0;
}
For the curious, the reason I want this is because the derived class implementation is using a utility class to memoize (add a cache around) the base-class implementation. The utility class takes a function pointer but, of course, the function pointer dispatches dynamically to the most derived class and I get an infinite recursion.
Is there a syntax that allows me to reproduce the static dispatch behaviour I can achieve with x->Base::foo()
but through a function pointer?
You could force the slicing of the Base*
like this:
std::cout << (static_cast<Base>(*x).*fooPtr)() << std::endl; // Outputs -1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With