Possible Duplicate:
Where and why do I have to put the “template” and “typename” keywords?
我想创建一个模板,它采用类型 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;
关于c++ - 用于指针生成的递归模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12263127/