简体   繁体   English

使用非模板化的类作为父级

[英]Use non-templated version of class as parent

I am working on porting a project from C# to C++ and am having an issue when using templates, I need to have both a non-templated and a templated version of a class with one parented to another, ie: 我正在努力将项目从C#移植到C ++,并且在使用模板时遇到问题,我需要同时拥有一个非模板化版本和一个模板化版本,其中一个类别是另一个类别,即:

class DataBuffer // Holds generic databuffer functions (getting size in bytes etc)
{
public:
    int32 getVal() { return 10; }
};

template <typename T>
class DataBuffer<T> : public DataBuffer // Able to retrieve data as a type...
{
public:
    int32 getSizeOfT() { return sizeof(T); }
};

I have methods that accept any type of DataBuffer as a parameter, so templating the entire class is not possible, is there any way of doing this without renaming the base class? 我有接受任何类型的DataBuffer作为参数的方法,因此模板化整个类是不可能的,有没有办法在不重命名基类的情况下这样做?

Any help would be greatly appreciated. 任何帮助将不胜感激。

EDIT: This code does not compile, and throws the following error at compile time: 编辑:此代码不编译,并在编译时抛出以下错误:

error C2989: 'DataBuffer' : class template has already been declared as a non-class template

Unfortunately, there is no way of doing so. 不幸的是,没有办法这样做。 I think the relevant portion of the standard is: 我认为标准的相关部分是:

A class template shall not have the same name as any other template, class, function, object, enumeration, enumerator, namespace, or type in the same scope (3.3), except as specified in (14.5.4). 除(14.5.4)中指定的情况外,类模板不得与同一范围(3.3)中的任何其他模板,类,函数,对象,枚举,枚举器,命名空间或类型具有相同的名称。 Except that a function template can be overloaded either by (non-template) functions with the same name or by other function templates with the same name (14.8.3), a template name declared in namespace scope or in class scope shall be unique in that scope. 除了函数模板可以由具有相同名称的(非模板)函数或具有相同名称的其他函数模板(14.8.3)重载之外,在命名空间作用域或类作用域中声明的模板名称在那范围。

However, the methods that should accept every type of DataBuffer could be made template too, so that inheriting from a common base would become unnecessary. 但是,应该接受每种类型的DataBuffer也可以成为模板,因此从公共库继承将变得不必要。

As the error says, a class template can't have the same name as a non-template. 如错误所示,类模板不能与非模板具有相同的名称。

You will have to rename either the base class or the template. 您必须重命名基类或模板。

您需要为类和类模板提供不同的名称或将它们放入不同的名称空间:类和类模板不能具有完全相同的名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM