如何正确声明自引用模板类型? [英] How to properly declare a self-referencing template type?
问题描述
如何声明引用自身的模板类型?
模板< class T = Animal>动物类{上市:T getChild();}
这样,我得到一个有关缺少类型说明符的编译器错误.我试图向前声明 Animal
,但没有成功.
我试图强加类型约束. Lion
只能有一个 Lion
作为孩子,一个 Bear
有一个 Bear
,依此类推./p>
编辑
我将发布实际课程的一部分.它是可以出现在链接列表中的类的模板:
模板< class T =链接的< T>>类链接{私人的:T * m_prev;T * m_next;}
我要强制该类只能指向同一类(或子类)的对象.
做类似链表的常用方法是:
模板< class T>类链接{私人的:链接的T * m_prev;链接的T * m_next;}
这对您有用吗?如果没有,那么您试图完成的工作无法通过这种方式完成吗?
How do I declare a templated type that refers to itself?
template <class T = Animal> class Animal
{
public:
T getChild ();
}
With this, I get a compiler error concerning a missing type specifier. I tried to forward-declare Animal
, without success.
I am trying to impose a type constraint. A Lion
can only have a Lion
as a child, a Bear
has a Bear
, and so on.
EDIT
I'll post part of the actual class. It is a template for classes that can appear in a linked list:
template <class T = Linked<T> > class Linked
{
private:
T* m_prev;
T* m_next;
}
I want to enforce that the class can only point to object of the same class (or a subclass).
The usual way to do something like a linked list is:
template <class T> class Linked
{
private:
Linked<T>* m_prev;
Linked<T>* m_next;
}
Does this work for you, and if not, what are you trying to accomplish that can't be done this way?
这篇关于如何正确声明自引用模板类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!