【发布时间】:2010-08-11 10:17:54
【问题描述】:
翻看一棵二叉树的源码,发现如下函数:
//definition of BTR,in case you'd want to know
template< class Type>
struct BTR
{
// The item saved to that specifiec position into the tree
Type value;
// Points to the left leaf
BTR<Type>* left;
// Points to the right leaf
BTR<Type>* right;
};
//why typename?
template< class Type>
BTR<Type>* CreateEx(typename const std::vector<Type>::iterator start,typename const std::vector<Type>::iterator end)
{
//definition
}
现在,这个函数让我感到困惑的是它的参数。 为什么需要关键字 typename? 因为如果我删除了两个类型名,我的编译器就会开始抱怨并说我应该在标识符“开始”之前放一个“)”。 如果我更改了参数,使函数采用两个向量而不是两个迭代器并删除了类型名,我的编译器就会停止抱怨(当然,该函数不再工作了)。
// perfectly acceptable!
template< class Type>
BTR<Type>* CreateEx( const std::vector<Type> start, const std::vector<Type> end)
看来我需要关键字,因为该函数需要两个迭代器。 但是为什么在这种情况下这个关键字是必要的呢?
【问题讨论】:
标签: c++ templates vector iterator typename