我有一种情况,我想要一个成员函数指针指向一个虚拟函数,以避免动态分派。请看下图:通过成员函数指针调用基础成员函数实现指向虚函数
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;
}
对于好奇,我想这是因为派生类的实现使用工具类memoize的原因(添加缓存周围)的基类实现。实用程序类采用函数指针,但是,当然,函数指针动态分派到大多数派生类,并且我得到无限递归。
是否有一种语法可以让我重现静态调度行为,我可以通过x->Base::foo()
来实现,但通过函数指针?
有趣......但是这实际上是调用了巴斯e复制构造函数仅适用于某些情况。如果Base具有私有拷贝构造函数或任何纯虚函数,则此解决方案将不适用。 – SimonD