【发布时间】:2015-06-28 06:26:43
【问题描述】:
我有一种情况,我想要一个指向避免动态分派的虚函数的成员函数指针。见下文:
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;
}
出于好奇,我想要这样做的原因是派生类实现使用实用程序类来记忆(添加缓存)基类实现。实用程序类需要一个函数指针,但当然,函数指针会动态分派给最派生的类,我会得到一个无限递归。
是否有一种语法可以让我重现我可以使用x->Base::foo() 但通过函数指针实现的静态调度行为?
【问题讨论】:
标签: c++ member-function-pointers