Sim*_*onD 5 c++ member-function-pointers
我有一种情况,我想要一个成员函数指针指向虚拟函数,避免动态调度.见下文:
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;
}
Run Code Online (Sandbox Code Playgroud)
对于好奇,我想要的原因是因为派生类实现使用实用程序类来记忆(添加缓存)基类实现.实用程序类采用函数指针,但是,当然,函数指针动态调度到最派生类,我得到无限递归.
是否有一种语法允许我重现我可以x->Base::foo()通过函数指针实现的静态调度行为?
您可以像这样强制切片Base*:
std::cout << (static_cast<Base>(*x).*fooPtr)() << std::endl; // Outputs -1
Run Code Online (Sandbox Code Playgroud)