函数模板和迭代器

function template and iterators

我有一个简单的函数模板,它应该将容器作为其模板参数并打印内容:

template <typename T>
void print(typename T::iterator &it1,typename T::iterator &it2)
{
  while (it1 != it2) {
    std::cout<<*it1<<" ";
    ++it1;
  }
}

我正在传递一个迭代器范围(通常是第一个迭代器和尾部迭代器)并且我将 typename 关键字添加到函数参数中,因为编译器需要知道我在谈论一个类型并且不是静态成员。

但是当我将一个向量传递给函数时,编译器说它找不到调用的任何匹配项(最接近的匹配项是函数本身) 怎么可能?

vector<double> dvec;
vector<double>::iterator it_b=dvec.begin();
vector<double>::iterator it_e=dvec.end();
print_it2(it_b,it_e);

编译器说:

template argument deduction/substitution failed
                    could not deduce template parameter T

typename T::iterator 是非推导上下文。编译器无法知道应该推导哪个 T,因为它不理解类型成员 iterator 和给定的 T 之间的语义联系。它需要搜索所有类型以找到匹配项并能够以某种方式消除冲突的歧义。这是不合理的,所以标准不允许。

您可以明确提供类型:

print<vector<double>>(it_b, it_e);
print<decltype(dvec)>(it_b, it_e); //c++11

但是忘记迭代器来自的容器并让编译器推断迭代器类型可能会更容易:

template <typename It>
void print (It& it1, It& it2);

也许您有理由通过引用传递迭代器,但似乎您应该改为通过值传递:

template <typename It>
void print (It it1, It it2);