c++ - 模板化方法的继承

标签 c++ templates inheritance

我有一个关于继承和模板方法的问题。假设我有这两个类

class Base
{
public:
   template<typename T>
   void print(const T& s) {std::cout << "Base (templated) prints " << s << "\n";}
   virtual void print(int i) {std::cout << "Base prints " << i << "\n";}
};

class Derived : public Base
{
public:
   void print(int i) {std::cout << "Derived prints " << i << "\n";}
}

int main()
{
   Derived d;
   d.print(3);     // works fine
   std::string s = "hi";
   d.print(s);  // does not compile
   return 0;
}

编译器告诉我“没有匹配函数来调用‘Derived::print(std::string&)’”。 但是 Derived,继承自 Base,应该也允许调用模板方法 print(..),不是吗?

事情也很奇怪,因为如果我没有在派生类中定义方法“print”,那么一切正常,编译器调用基类模板方法。

如果我也在派生类中定义模板方法,事情也能正常工作,它调用基类一,但这对我来说似乎不正确......

感谢您的帮助。

最佳答案

在派生类中声明一个函数会隐藏基类中同名的所有函数。您可以使用 using 声明取消隐藏它们:

class Derived : public Base
{
public:
    // Add this
    using Base::print;

    void print(int i) {std::cout << "Derived prints " << i << "\n";}
}

关于c++ - 模板化方法的继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12304670/

相关文章:

c++ - std::bitset 的二进制序列化

实现 C++ 接口(interface)的 C# COM 程序集

c++ - Windows 程序的调用约定最好声明什么?

c++ - 除非使用,否则为什么不初始化静态模板字段?

php - 使用 tpl 的 php 模板中的 if 语句

c++ - 为 T 类型的容器专门化一个模板

c++ - 指针和数组 - C++

c++ - 如何在父类函数中使用继承对象?

c++ - using 声明是否应该隐藏继承的虚函数?

c++ - 从类的 QList 访问 protected 成员,例如 QList<Account*>