我试图重载一个特定的函数,因此只有连续容器的迭代器(即std::vector::iterator、std::array::iterator和内置数组迭代器==原始指针)才是有效的参数。
由于某些原因,我的函数无法编译向量和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 我正在使用VC++与VisualStudio2015RTM。
这些错误是不言自明的,但我想知道编译器是否真的不能从它和it0中推断T和N,毕竟它是它/ it 0类型的一部分。
怎样才能让它发挥作用?
编辑:
我将使用@ arguments建议,并将容器+迭代器/索引作为参数传递。谢谢!
发布于 2016-01-15 14:21:25
您的函数无法工作,因为编译器无法从迭代器中推断出发送到函数的T和N。您可以使用std::enable_if。
template <class Iterator>
typename std::enable_if<std::is_same<Iterator, typename std::array<typename std::iterator_traits<Iterator>::value_type, 1>::iterator>::value, void>::type
catchIterator(Iterator it) {
//do somthing
}
template <class Iterator>
typename std::enable_if<std::is_same<Iterator, typename std::vector<typename std::iterator_traits<Iterator>::value_type>::iterator>::value, void>::type
catchIterator(Iterator it) {
//do somthing
}但是,如果vector::iterator和array::iterator是相同类型的(例如gcc ),那么实际上存在一个问题--代码不能编译,因为编译器不知道它应该使用哪个函数。
最好的方法是传递容器作为第一个参数,迭代器作为第二个参数。
template <typename T, size_t N>
void catchIterator(const std::array<T, N> &, typename std::array<T, N>::iterator it) {
//do somthing
}
template <typename T>
void catchIterator(const std::vector<T> &, typename std::vector<T>::iterator) {
//do somthing
}https://stackoverflow.com/questions/34812856
复制相似问题