【问题标题】:c++ How do you call a template class function that is overloaded in the derived class, from the derived class?c++ 如何从派生类中调用派生类中重载的模板类函数?
【发布时间】:2012-06-20 20:44:00
【问题描述】:

有没有办法在派生类中重载基模板类函数,并且仍然能够调用基类函数,如下所述?

template <class A>
class testBase {

public:
  void insert() {
    // Whatever
  }
};

class testDerived : public testBase<double> {
private:

  void insert(int a) {
    // something
  }
};


int main() {

  testDerived B;

  // Compiler doesn't recognize overloaded insert,
  // How do you do this?
  B.insert();

}

【问题讨论】:

    标签: c++ templates inheritance name-hiding


    【解决方案1】:

    你遇到的问题叫做name-hiding

    您可以通过名称限定基类函数来调用它:

    B.testBase<double>::insert();
    

    或者通过“取消隐藏”它,通过在派生类中使用 using 声明来声明它:

    class testDerived : public testBase<double> {
    public:
      using testBase<double>::insert;
    private:
      void insert(int a) {
        // something
      }
    };
    

    【讨论】:

      【解决方案2】:

      添加

      public:
        using testBase<double>::insert;
      

      testDerived的定义。这将使基类的隐藏成员在派生类中可用

      【讨论】:

        猜你喜欢
        • 2021-03-19
        • 1970-01-01
        • 1970-01-01
        • 2015-12-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多