如何声明引用自身的模板类型?
template <class T = Animal> class Animal
{
public:
T getChild ();
}
Run Code Online (Sandbox Code Playgroud)
这样,我得到一个有关缺少类型说明符的编译器错误。我试图向前声明Animal,但没有成功。
我试图强加类型约束。A Lion只能有一个Lion孩子,a Bear有一个Bear,依此类推。
编辑
我将发布实际课程的一部分。它是可以出现在链接列表中的类的模板:
template <class T = Linked<T> > class Linked
{
private:
T* m_prev;
T* m_next;
}
Run Code Online (Sandbox Code Playgroud)
我要强制该类只能指向同一类(或子类)的对象。
OP 已经得到答复,但我想插话,因为问题的直接原因不是递归,正如其他人声称的那样。这行不通的最简单原因是类模板不是类型。它们是模板。同样,函数模板也不是函数。所以这一切都是无稽之谈:
template<typename T> int function_template(int);
typedef int function_type(int);
void eats_a_function(function_type&); // needs a reference to function
std::vector< std::vector > vec0; // std::vector is not a type
std::vector< std::list > vec1; // std::list is not a type
eats_a_function(function_template); // function_template is not a function
Run Code Online (Sandbox Code Playgroud)
请注意,在本vec1例中,std::list与 无关std::vector。模板在实例化时已完全定义(假设包含标头)。它仍然行不通。
相反,以下工作有效:
std::vector< std::vector<int> > vec2; // std::vector<int> is a type
std::vector< std::list<double> > vec3; // std::list<double> is a type
eats_a_function(function_template<long>); // function_template<long> is a function
Run Code Online (Sandbox Code Playgroud)
请注意,在 vec2 情况下,可以传递模板本身的实例化。
作为记录,使用众所周知的间接层编写引用自身的模板时解决玩具问题的玩具解决方案:
// expects a template that expects a type
template<template<class> class T> struct indirection {};
// forward decl. for defaulting the parameter
template<typename T> struct recursive;
// template that expects a type
template<typename T = indirection<recursive> > struct recursive {};
Run Code Online (Sandbox Code Playgroud)
考虑到模板可以实现的一些功能(T里面的参数indirection),它的功能并不是非常强大。当然可以编写一个rebind返回 的实例化的 -style 元函数T。
执行链接列表之类的操作的通常方法是:
template <class T> class Linked
{
private:
Linked<T>* m_prev;
Linked<T>* m_next;
}
Run Code Online (Sandbox Code Playgroud)
这对你有用吗?如果没有,你想完成什么是无法通过这种方式完成的?