【问题标题】:Passing an iterator to a function将迭代器传递给函数
【发布时间】: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


【解决方案1】:

因为编译器不知道 std::vector::iterator 是 std::vector 的类型还是成员,因此需要一点帮助类型名的形式。

【讨论】:

    猜你喜欢
    • 2013-06-03
    • 2014-06-26
    • 2013-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-02
    • 1970-01-01
    • 2015-04-15
    相关资源
    最近更新 更多