c++ How do you call a template class function that is overloaded in the derived class, from the derived class?

StackOverflow https://stackoverflow.com/questions/11127890

Вопрос

Is there a way to overload base template class functions in derived classes, and still be able to call the base class function, as described below?

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();

}
Это было полезно?

Решение

The problem you've encountered is called name-hiding.

You can call the base class function by qualifying it by name:

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

Or by "un-hiding" it, by declaring it in the derived class with a using declaration:

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

Другие советы

Add

public:
  using testBase<double>::insert;

to the definition of testDerived. This will make the hidden members of the base available in the derived class

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top