我正在尝试使用std::bind()创建一个函数,该函数将调用基类版本的虚函数,而不是调用派生类的版本。
struct Base
{
virtual void foo() { cout << "Base\n"; }
};
struct Derived : public Base
{
virtual void foo() { cout << "Derived\n"; }
};
int main(int argc, const char * argv[])
{
Base* base = new Derived;
auto baseMethodHopefully = std::bind( &Base::foo, base );
baseMethodHopefully(); // Want call to Base::foo(), but get call to Derived::foo().
return 0;
}
我从其他地方了解到,通常情况下您无法以“反虚拟”的方式调用基函数,例如此处。明显的例外是常见的范例:
void Derived::bar() { Base::bar(); }
由于在Derived的方法中,表达式Base::bar()
被认为是“反虚拟化”的(我所指的意思),因此是否可能从Derived的某个方法内以期望的方式绑定到Base::bar()
?例如,像这样:
void Derived::bar()
{
auto baseMethod = std::bind( &Base::foo, this );
baseMethod();
}
如果是这样,语法是什么?
如果是这样,语法是什么?
Base::bar()
设为非虚成员函数呢? - John