是否可以在 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/