带迭代器的模板函数

Template function with iterators

本文关键字:函数 迭代器      更新时间:2023-10-16

我一直在尝试在加速c++中执行Ex. 10-02,它给了我错误,我最终一直在"简化"我的程序,直到我达到这一点,甚至它仍然无法编译(通过g++)给我错误:

test.cpp: In function ‘int main()’:
test.cpp:22: error: no matching function for call to ‘dumb(__gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >, __gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >)’

这是我的程序:

#include <algorithm>
#include <iostream>
#include <vector>
using std::cout;    using std::endl;
using std::vector;
template <class Ran, class T> T dumb(Ran begin, Ran end)
{
    return *begin;
}
int main()
{
    vector<int> myVector;
    for (int i = 1; i <= 9; ++i)
        myVector.push_back(i);
    int d = dumb(myVector.begin(), myVector.end());
    cout << "Value = " << d << endl;
    return 0;
}

是什么导致这个错误?

编译器不能推断这里的返回类型。实际上,这里没有必要将返回类型设置为模板参数:

template <class Ran> typename Ran::value_type dumb(Ran begin, Ran end)
{
    return *begin;
}

问题是你的函数原型:

template <class Ran, class T> T dumb(Ran begin, Ran end)

当使用template s时,返回类型是依赖类型(这里是T),不能隐式地推导

所以你重新设计的功能应该是这样的:

template <class T, class Ran>
          // ^^^^^ 'T' is coming before 'Ran'
T dumb(Ran begin, Ran end)
{
  return *begin;
}

应该命名为

int d = dumb<int>(myVector.begin(), myVector.end());
             ^^^^

我们做了2个改动:

  1. 需要明确提及的类型(即T=int)为未来1
  2. 调用dumb<>时明确提到int,因此返回类型是可扣除的

[注意:这个解决方案对于你的理解来说是非常通用的。正如@Bjorn的回答中提到的,对于vector<>,类型可以使用::value_type自动推断[/p>