我有一種情況,我想要一個成員函數指針指向一個虛擬函數,以避免動態分派。請看下圖:通過成員函數指針調用基礎成員函數實現指向虛函數
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