带有继承列表的 C++ 模板声明

标签 c++ templates inheritance declaration c++03

是否可以在 C++ 中声明模板化类及其继承的类?基本上我想给编译器一个提示,我的模板类总是在声明时继承另一个。 也许一些代码会弄清楚为什么这对我来说是个问题:

template<typename T>
class GrandparentClass
{
public:
    T grandparentMember;
};

//this needs to be only a declaration, since I do not want classes of ParentClass with random T
template<typename T>
class ParentClass : public GrandparentClass<T>
{

};

// this does not work:
//template<typename T>
//class ParentClass : public GrandparentClass<T>;

// this does not either, because then the child class cannot access the variable from the grandparent class
//template<typename T>
//class ParentClass;

template<>
class ParentClass<int> : public GrandparentClass<int>
{
public:
    ParentClass()
    {
        grandparentMember = 5;
    }
};

template <typename T>
class ChildClass : public ParentClass<T>
{
public:
    void foo()
    {
        std::cout << grandparentMember << "\n";
    }
};

另外,我不能使用 C++ 11。

编辑:

我找到了一个简单的方法:

template<typename T>
class ParentClass : public GrandparentClass<T>
{
public:
    ParentClass() { ParentClass::CompilerError(); };
};

只要不在类中定义 CompilerError() 方法就可以了。

最佳答案

类声明仅对非值变量声明真正有用,例如指针和引用。但是,您不能访问类成员,甚至不能实例化它。即使您知道一个已声明的类继承自其他某个类,您仍然不一定能够以任何方式利用该信息。

因此,对于编译器来说,只有在了解类的完整定义后才知道类继承自什么才是重要的。


在评论中澄清之后:如果你想阻止实例化具有某些类型的类模板,它的定义就是这样做的地方。类体内的一个简单的 static_assert 就可以解决问题; Boost.StaticAssert 或更早的 SFINAE 技巧将完成 C++11 之前代码的工作。

关于带有继承列表的 C++ 模板声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45347731/

相关文章:

c++ - 程序编译、运行,但不会在 DevC++ 中结束

c++ - 使用 Qt5 为 ARM 交叉编译时的静态 libstdc++

css - django 样式表不与图像文件链接

swift - 有没有办法一起使用模板、输入输出参数和可选参数?

java - 如何区分父类(super class)的ArrayList中的子类

java - 为什么父类(super class)分配给子类会出错?

c++ - 函数调用导致无输出

c++ - DEP (/NXCOMPAT) 在 LoadLibrary 中导致段错误(在 DllMainCRTStartup 中向下)

C++ 部分特化不适用于不同大小的特征矩阵

javascript - Javascript 中的原型(prototype)有什么作用?