带有模板的C++继承

C++ inheritance with templates

本文关键字:C++ 继承      更新时间:2023-10-16

EDIT:这只是另一个"愚蠢和无趣的错误"。您已收到警告:)

这是让我彻夜难眠的东西。也许有更高C++知识的人可以找到如何让它发挥作用:

template<class T>
class Base
{
    virtual void Method ( T* arg ) = 0;
};
class Child : public Base<MyType>
{
    void Method ( MyType* arg ) { /*blah*/ };
};

这不会编译(至少在VS2008上不会),因为它无法将这两个方法匹配在一起。

目前,我们通过在方法声明中使用BaseType而不是MyType来解决这个问题,然后在方法的Child实现中将BaseType强制转换为MyType(我们仍然需要MyType作为基类中其他内容的模板)。

不过,如果能够直接使用模板化类型,那就太好了。

编辑:谢谢,伙计们,修复其他错误(后面列出的)似乎让一切都成功了。在我的原始代码中,我确实使用了template<class T>而不是template<T>,并且方法列为public。这表明我应该等待更长的时间才能发帖。我为此道歉。

以下是编译并运行良好的完整示例:

struct MyType
{
};
template< class T>
class Base
{
public:
    virtual void Method ( T* arg ) = 0;
};
class Child : public Base<MyType>
{
  public:
    void Method ( MyType*  ) { /*blah*/ };
};

int main()
{
  MyType a;
  Child b;
  b.Method( &a );
}

您需要在第一个类模板中使用正确的语法:

template<typename T> // here! You can also use "class" instead of "typename".
class Base
{
    virtual void Method ( T* arg ) = 0;
};

第二个类必须是一个类模板,除非MyType是一个类型:

template <typename MyType>
class Child : public Base<MyType>
{
    void Method ( MyType* arg ) { /*blah*/ };
};

在第一行写入template<class T>而不是template<T>。这样就可以了。

为了获得所需的结果,您需要将基类方法公开为

   template<class T> class Base
    {
        public: // public definition is important or else it won't be overridden
        virtual void Method ( T* arg ) {
            cout << "Method in base.";
        }
    };
class Child : public Base<char>
{
    void Method ( char* arg ) {
       cout << "Method in child.";
    };
};