c++ - 关于模板中随机访问迭代器的运算符+重载的问题

标签 c++ templates iterator overloading operator-keyword

我想重载列表类中迭代器的“+”运算符,例如

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'

不知道原因...

代码附在下面,

#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 这是推进迭代器的惯用方法。

关于c++ - 关于模板中随机访问迭代器的运算符+重载的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6793137/

相关文章:

c++ - 你可以 pop_back 一个 vector 并仍然使用迭代器到最后一个元素吗?

c++ - 反斜杠和引号不计入字符串长度?

c++ - 使用选择排序根据玩家点数对列表进行排序?

javascript - 为什么 Dreamweaver 显示此脚本行的语法错误?

c++ - 模板特化是否需要 template<> 语法?

rust - 在结构中存储HashMap的迭代器

C++ - 创建数组的低通滤波器函数

c++ - C++中的文件锁定用于同时读取和写入锁定

c++ - 多种类型的模板方法特化

java - 在 Java 中克隆迭代器