Eri*_*ric 1 c++ templates iterator vector typename
查看二叉树的源代码,我找到以下函数:
//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
}
Run Code Online (Sandbox Code Playgroud)
现在,让我对这个功能感到困惑的是它的参数.为什么需要关键字typename?因为如果我删除这两个类型名称,我的编译器开始抱怨并说我应该在标识符'start'之前加上')'.如果我更改了参数以便函数使用两个向量而不是两个迭代器并删除了类型名称,我的编译器就会停止抱怨(当然,该函数不再起作用).
// perfectly acceptable!
template< class Type>
BTR<Type>* CreateEx( const std::vector<Type> start, const std::vector<Type> end)
Run Code Online (Sandbox Code Playgroud)
所以我似乎需要关键字,因为该函数需要两个迭代器.但是为什么在这样的情况下这个关键字是必要的呢?
因为编译器不知道std :: vector <Type> :: iterator是std :: vector <Type> 的类型还是成员,因此需要以typename的形式提供一些帮助.