我将尝试重载某个函数,以便仅接受连续容器的迭代器作为有效参数(这些容器包括std::vector::iterator,std::array::iterator和内建数组迭代器==原始指针)。
但是出于某种原因,我的函数在处理vector和std::array时无法编译:
函数如下:
template <class T,size_t N>
void catchIterator(typename std::array<T, N>::iterator it) {
//do somthing
}
template <class T>
void catchIterator(typename std::vector<T>::iterator it) {
//do somthing
}
使用示例:
std::array<int, 10> arr;
auto it = arr.begin();
catchIterator(it);
std::vector<int> vec;
auto it0 = vec.begin();
catchIterator(it0);
错误:
Error (active) no instance of overloaded function "catchIterator" matches the argument list
Error (active) no instance of overloaded function "catchIterator" matches the argument list
Error C2783 'void catchIterator(std::array<_Ty,_Size>::iterator)': could not deduce template argument for 'T'
Error C2783 'void catchIterator(std::array<_Ty,_Size>::iterator)': could not deduce template argument for 'N'
Error C2672 'catchIterator': no matching overloaded function found
我正在使用Visual Studio 2015 RTM版的VC++。
这些错误已经很明显了,但我想知道编译器是否不能从it和it0中真正推断出T和N,毕竟它是it/it0类型的一部分。
如何使它工作?
编辑:
我会采用@ForEveR的建议,将容器+迭代器/索引作为参数传递。谢谢!
catchIterator
时,才需要@DavidHaim。 - ForEveRstd::array<T,1u>::iterator === std::array<T,N>::iterator
。 - Pixelchemiststd::_Array_iterator<_Ty,N>
。 - Pixelchemist