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



是否可以在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 之前代码的工作。

如果您对将错误延迟到链接时间而不是编译时间感到满意,则可以在 parent.h 中声明 parent 的所有成员函数,在 parent.cpp 中提供定义,并显式实例化所需的类的有限列表。

家长.h

template<typename T>
class ParentClass : public GrandparentClass<T>
{
ParentClass();
};
class ParentClass<int>;
class ParentClass<long int>; // or whatever

家长.cpp

template <typename T>
ParentClass::ParentClass() : grandparentMember(5) {}

最新更新