关于模板中随机访问迭代器的操作符+重载的问题



我想重载列表类中迭代器的"+"操作符,类似于

list<double>::iterator operator+(const list<double>::iterator& it, int n)

这个效果很好。但是,当我尝试将其实现为模板时,如

template<class T>
typename list<T>::iterator operator+(const typename list<T>::iterator& it, int n)

我收到了错误信息

no match for 'operator+' in 'it + small_index'

can't figure out the reason…

代码附在下面,

#include<iostream>
#include<list>
using namespace std;
template<class T>
ostream& operator<< (ostream& os, const list<T>& l)
{
  typename list<T>::const_iterator i = l.begin();
  for (;i!=--l.end();i++)
    os<<*i<<";";
  os<<*i<<endl;
  return os;
}
template<class T> //this is where it goes WRONG.
                  //If don't use template, delete "typename", T->double, runs well
typename list<T>::iterator operator+(const typename list<T>::iterator& it, int n)
{
  typename list<double>::iterator temp=it;
  for(int i=0; i<n; i++)
    temp++;
  return temp;
}
template <class T>
void small_sort(list<T>& l)
{
  int n = l.size();
  typename list<T>::iterator it = l.begin();
  for(int i=0; i<n-1; i++)
    {
      //Find index of next smallest value
      int small_index = i;
      for(int j=i+1; j<n; j++)
    {
      if(*(it+j)<*(it+small_index)) small_index=j;
    }
      //Swap next smallest into place
      double temp = *(it+i);
      *(it+i) = *(it+small_index);
      *(it+small_index)=temp;
    }
}
int main()
{
  list<double> l;
  l.push_back(6);
  l.push_back(1);
  l.push_back(3);
  l.push_back(2);
  l.push_back(4);
  l.push_back(5);
  l.push_back(0);
  cout<<"=============sort the list=============="<<endl;
  small_sort(l);
  cout<<l;
  return 0;
}

问题是在这种情况下论证是不可演绎的。

template<class T>
typename list<T>::iterator operator+(const typename list<T>::iterator& it, int n);

当你在那里使用迭代器时,编译器将不得不生成具有任何给定类型的list的所有可能的实例化,并尝试与你传递的参数匹配内部类型iterator,请注意,一旦你添加模板到混合中,所有类型的集合实际上是无限的,因为你可以用同一个模板的实例化来实例化一个模板和无限

我建议您完全避免这个问题,并使用std::advance,这是推进迭代器的惯用方法。

您应该看看是否可以使用标准算法std::advance(it, n)。它在<iterator>中定义。它为任何合适的迭代器做"正确的事情"

最新更新