std :: bind与父类的重载函数

时间:2016-07-25 04:04:54

标签: c++ c++11 overloading stdbind

#include <iostream>
#include <functional>

class Base
{
    public:
        virtual ~Base() {}
        virtual void f1() const {std::cout<<"Base::f1() called"<<std::endl;}
        virtual void f1(int) const {std::cout<<"Base::f1(int) called"<<std::endl;}
        virtual void f2() const {std::cout<<"Base::f2() called"<<std::endl;}
};

class Derived : public Base
{
    public:
        virtual ~Derived() {}
        void f1() const {std::cout<<"Derived::f1() called"<<std::endl;}
};

int main()
{
    Base base;
    Derived derived;
    auto func1 = std::bind(static_cast<void(Base::*)()const>(&Base::f1), std::cref(base));
    func1();
    auto func2 = std::bind(static_cast<void(Derived::*)()const>(&Derived::f1), std::cref(derived));
    func2();
    auto func3 = std::bind(&Base::f2, std::cref(base));
    func3();
    auto func4 = std::bind(&Derived::f2, std::cref(derived));
    func4();
    auto func5 = std::bind(static_cast<void(Base::*)(int)const>(&Base::f1), std::cref(base), std::placeholders::_1);
    func5(1);
    auto func6 = std::bind(static_cast<void(Derived::*)(int)const>(&Derived::f1), std::cref(derived), std::placeholders::_1);  // error line
    func6(2);
    return 0;
}

当我尝试构建上面的代码时,gcc会给出以下错误消息。

  

test.cpp:34:80:错误:类型为'void的static_cast无效   (Derived :: )()const'类型'void(Derived :: )(int)const'

     

auto func6 = std :: bind(static_cast(&amp; Derived :: f1),   std :: cref(derived),std :: placeholders :: _ 1);

我想知道是否有任何方法可以通过类Base::f1(int)绑定Derived(在此成功绑定func6)。 任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:1)

如何使用&Derived::Base::f1代替&Derived::f1

我的意思是

auto func6 = std::bind(static_cast<void(Derived::*)(int)const>(&Derived::Base::f1), std::cref(derived), std::placeholders::_1); 

正如Oktalist(谢谢)所建议的那样,您也可以使用&Base::f1

它更简单。