指针生成的递归模板
Recursive template for pointer generation
可能重复:
我必须将“模板”以及“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***
}
编译器告诉t
是dependent name
,所以在ptr<T*, (N - 1)>::t
之前使用typename
相关文章:
- 在对象指针上调用 Delete 是否会递归删除其动态分配的成员
- 为什么编译器将其解析为函数指针而不是递归调用?
- 如何通过函数指针递归调用类成员函数?
- 使用双指针和递归反转链表
- 使用带有递归的指针
- 有没有办法在递归中使用指针来查找数组的最小值?
- 具有 4 个指针的节点的递归插入函数返回 null
- 共享指针中的递归,而变量在类中定义
- 尝试使用递归和指针到指针反转链表,但反转函数没有给出预期的正确输出
- 指针似乎迷失在递归算法中
- 为什么这种递归子集和算法会导致指针分配错误
- 没有指针的递归结构?(霍夫曼)
- 从 'int' 到 'int*' 的转换无效(尝试使用指针进行递归)
- 通过递归正确传递指针的值
- 通过类型C++ 的继承树递归导致此指针问题
- 是否有可能有一个指针指向由奇怪的递归模板创建的基类
- c++ 递归树 使用指针和状态机构建树
- 指针生成的递归模板
- 递归插入到二叉树中,按值传递指针
- C++递归指针函数调用