Old*_*ier 9 c++ virtual-functions bind member-function-pointers c++11
我试图使用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;
}
Run Code Online (Sandbox Code Playgroud)
我从其他地方了解到你通常不能以"反虚拟"方式调用基本功能,例如这样.一个明显的例外是常见的范例:
void Derived::bar() { Base::bar(); }
Run Code Online (Sandbox Code Playgroud)
由于表达Base::bar()
被认定为"反虚"(在这个意义上,我暗指)派生的方法中,是可以绑定到Base::bar()
从希望的方式内源性的方法之一?例如:
void Derived::bar()
{
auto baseMethod = std::bind( &Base::foo, this );
baseMethod();
}
Run Code Online (Sandbox Code Playgroud)
如果是这样,语法是什么?
asc*_*ler 15
好吧,&Base::foo
是一个成员函数指针.并且无法使用不调用虚拟覆盖的成员函数指针.避免虚拟覆盖的唯一语法是类名,函数名和参数列表都在同一表达式中的语法.
但如果你有std::bind
,你可能也有lambdas,所以也许你可以使用:
auto baseMethod = [this](){ return Base::foo(); };
//...
baseMethod();
Run Code Online (Sandbox Code Playgroud)