Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call base member function implementation through member function pointer to virtual function [duplicate]

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?

like image 614
SimonD Avatar asked Nov 10 '22 15:11

SimonD


1 Answers

You could force the slicing of the Base* like this:

std::cout << (static_cast<Base>(*x).*fooPtr)() << std::endl; // Outputs -1
like image 139
TartanLlama Avatar answered Nov 15 '22 04:11

TartanLlama