C++ 如何使用std::bind()调用基类';虚拟函数的s版本?

C++ 如何使用std::bind()调用基类';虚拟函数的s版本?,c++,c++11,bind,virtual-functions,member-function-pointers,C++,C++11,Bind,Virtual Functions,Member Function Pointers,我试图使用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[]) {

我试图使用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;
}
由于表达式
Base::bar()
在派生的方法中被识别为“反虚拟”(在我所指的意义上),那么是否可以从派生的方法中以所需的方式绑定到
Base::bar()
?例如,类似于:

void Derived::bar()
{
    auto baseMethod = std::bind( &Base::foo, this );
    baseMethod();
}

如果是,语法是什么?

那么,
&Base::foo
是一个成员函数指针。而且,无法使用不调用虚拟重写的成员函数指针。避免虚拟重写的唯一语法是类名、函数名和参数列表都位于同一表达式中的语法

但是如果您有
std::bind
,那么您可能也有lambda,因此您可以使用:

auto baseMethod = [this](){ return Base::foo(); };
//...
baseMethod();

好极了。工作起来很有魅力。谢谢对不起,我没听懂。你怎么能在没有对象的情况下创建一个成员函数呢?lambda表达式只能在
Base
Derived
(或
Base
的另一个子类)的成员函数中工作,并在我的编译器(Apple LLVM compiler 4.1)上捕获
是必需的,或者我收到一个错误:“错误:无法在此上下文中隐式捕获:'此'。”因此,我先前的编辑。是的,
[this]
是必需的。已编辑。
auto baseMethod = [this](){ return Base::foo(); };
//...
baseMethod();