【问题标题】:std::bind with overloaded function from parent classstd::bind 与父类的重载函数
【发布时间】:2016-11-28 07:28:12
【问题描述】:
#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(&Derived::f1), std::cref(派生), std::placeholders::_1);

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

【问题讨论】:

  • 您的意思是将Derived::f1 标记为override
  • @Tas 你不需要写override。如果基类中存在具有相同签名的虚函数,它会隐式覆盖。只有确定覆盖你写的override
  • Derived 中添加using Base::f1; 将起作用。 c++ issue with function overloading in an inherited class 的可能重复项
  • @neuront 这假设@qdtang 能够更改derived 的定义。我投票决定保持开放,因为对我来说,问题似乎是关于如何在bind 通话中做到这一点。
  • @neuront 您的解决方案确实有效。但我不认为我的问题与您提到的问题重复,因为我的方法是虚拟的。但是this thread 解释说即使是虚函数覆盖也会隐藏父类中的所有重载函数,这解决了我的困惑。感谢所有评论

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


【解决方案1】:

&amp;Derived::Base::f1 代替&amp;Derived::f1 怎么样?

我是说

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

按照 Oktalist 的建议(谢谢),您也可以使用 &amp;Base::f1

它甚至更简单。

【讨论】:

  • @Oktalist - 你是对的;谢谢。修改了我的答案。
  • 感谢您的帖子。该解决方案也可以正常工作。但我担心的是用户(执行此绑定)需要了解有关类层次结构的更多详细信息才能这样编写。我认为在用户不知道细节的情况下使用自己的方法版本会更好。
猜你喜欢
  • 1970-01-01
  • 2012-10-15
  • 1970-01-01
  • 2014-09-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多