带有模板的C++继承
C++ inheritance with templates
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.";
};
};
相关文章:
- 继承函数的重载解析
- 继承期间显示未知行为的子类
- 头文件-继承c++
- 为什么在保护模式下继承升级不起作用
- 通过继承类使用来自不同命名空间的运算符
- 子目录是否继承属性,例如add_definitions,include_directories和父Cmakelist.t
- 混合组合和继承的C++问题
- 继承:构造函数,初始化C++11中基类的类C数组成员
- 从类继承时,继承的类是否会通过父类重新定义继承的变量
- 公共与私人继承
- 如何创建从同一类继承的不同对象的向量
- 如何从另一个文件继承私有成员变量和公共函数
- 在模板基类中为继承类中的可选重写生成虚拟方法
- 带有继承的C++工厂
- 我应该避免多重实现继承吗
- C++继承更改成员
- 从具有默认值的部分指定模板类继承时发生SWIG错误,具有不带默认值的正向声明
- 关于C++中具有多重继承"this"指针的说明
- 尝试使用继承和模板实现CRTP.Visual Studio正在生成编译器错误
- 如何在QT Creator上将QWidget声明为继承类的对象