c++ - 将迭代器传递给函数

标签 c++ templates vector iterator 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
}

现在,让我困惑的是这个函数的参数。 为什么需要关键字 typename? 因为如果我删除这两个类型名称,我的编译器就会开始提示并说我应该在标识符“开始”之前放置一个“)”。 如果我更改了参数,使函数使用两个 vector 而不是两个迭代器并删除了类型名,我的编译器就会停止提示(当然,该函数不再起作用)。

// perfectly acceptable!
template< class Type>
BTR<Type>* CreateEx( const std::vector<Type> start, const std::vector<Type> end)

看来我需要关键字,因为函数需要两个迭代器。 但是为什么在这种情况下需要这个关键字呢?

最佳答案

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

关于c++ - 将迭代器传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3457325/

相关文章:

c++ - ShowWindow 无效的窗口句柄

c++ - x86 EXE 中是否有分配 winapi 调用?

c++ - VS2013 上出现 SFINAE 错误?

json - Opsworks实例启动失败: Status: start_failed: No such cookbook: apt

c++ - 如何使用模板推导 std::function 的参数类型?

image - 什么是图像矢量?

c++ - 尝试设置 QQmlListProperty 时出错

c++ - 下限误差

vector - GLSL 齐次转换问题

c++ - 以非侵入式方式用表达式树替换自定义类型