指针生成的递归模板

Recursive template for pointer generation

本文关键字:递归 指针      更新时间:2023-10-16

可能重复:
我必须将“模板”以及“typename;关键词?

我想创建一个模板,它以类型T和参数N为自变量,并为T"给出"第N级的指针(例如,如果T是int,N是2,它应该给出int**

到目前为止,我的代码是:

template<class T,int N>
struct ptr
{
  typedef ptr<T*,N-1>::t t;
};
template<class T>
struct ptr<T,0>
{
  typedef T t;
};
int main()
{
  ptr<int,3>::t a; //a should be int***
}

但它给了我一个编译器错误:

source.cpp:6:11: error: need 'typename' before 'ptr<T*, (N - 1)>::t' because 'ptr<T*, (N - 1)>' is a dependent scope

这意味着什么?如何修复它(如果在C++中可能的话)?

该错误意味着ptr<T*, (N - 1)>::t依赖名称

模板定义中使用的t的含义取决于模板参数,因此编译器无法自动确定t是类型而不是对象。

要更正错误,您必须给编译器一个提示,即按照消息的建议执行操作:在其前面加上typename

typedef typename ptr<T*,N-1>::t t;
template<class T,int N>
struct ptr
{
  typedef typename ptr<T*,N-1>::t t;
};
template<class T>
struct ptr<T,0>
{
  typedef T t;
};
int main()
{
  ptr<int,3>::t a; //a should be int***
}

编译器告诉tdependent name,所以在ptr<T*, (N - 1)>::t 之前使用typename