c++ - 使用类的非模板版本作为父类

标签 c++ visual-studio templates

我正在将一个项目从 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); }
};

我有接受任何类型的 DataBuffer 作为参数的方法,因此不可能对整个类进行模板化,有没有什么方法可以在不重命名基类的情况下做到这一点?

如有任何帮助,我们将不胜感激。

编辑: 此代码不编译,并在编译时抛出以下错误:

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

最佳答案

不幸的是,没有办法这样做。我认为标准的相关部分是:

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). 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.

但是,应该接受每种类型的 DataBuffer 的方法也可以做成模板,这样就不需要从公共(public)基础继承了。

关于c++ - 使用类的非模板版本作为父类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20616627/

相关文章:

c++ - 带类(class)的二十一点模拟器

c++ - 通过仿函数断开 boost 信号 2 连接

visual-studio - 如何在 Visual Studio 2010 及更高版本中重置 Zoom

templates - 遍历数组的元组

.net - 测试 Wpf Control 实例化性能

jquery - 使用 jQuery 模板动态创建 jQuery Mobile 页面

c++ - 从服务器下载后如何解压缩三星bada中的压缩目录

c++ - 以编程方式退出 MFC 应用程序的正确方法是什么?

c - 我的 C "Hello, world!"程序没有编译

.net - 如何构建共享项目