【发布时间】:2017-07-27 10:11:24
【问题描述】:
是否可以在 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() 方法,一切都很好。
【问题讨论】:
-
是的,应该可以。您认为问题在哪里?
-
没有。类声明取自
class foo;。无论是否模板,这都不能包含基类。即使可以,专业化仍然必须再次包含它。 -
问题是你不能把定义改成
template<typename T> class ParentClass : public GrandparentClass<T>;我在代码里编辑一下 -
为什么要给编译器这样的提示?无论如何,编译器在知道具体的参数分配之前不会解释声明,所以它没有用这样的提示。
-
我想禁止使用与我专门针对的类型名称不同的类型名称来实例化 ParentClass,而祖父母成员仍然应该可以从子类访问。基本上我不想为任何 T 提供 ParentClass 的定义,只是针对特定类型。
标签: c++ templates inheritance declaration c++03