C ++模板不会接受迭代器 [英] C++ template won't accept iterators

查看:230
本文介绍了C ++模板不会接受迭代器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在重新学习C ++,并开始尝试应该是一个简单的算法:QuickSort。我的函数有这个签名:

I'm re-learning C++, and have started by trying what should be a simple algorithm: QuickSort. My function has this signature:

template <class T>
void QSort(typename std::vector<T>::iterator begin, typename std::vector<T>::iterator end)

它在我的主要函数中调用:

And it is called in my main function:

int main()
{
    std::vector<int> unsort({56,32,11,45,67,81,12,5});
    std::vector<int>::iterator b=unsort.begin();
    std::vector<int>::iterator e=unsort.end();
    QSort(b, e);
    return 0;
}

并发生此错误:

C:\Users\Deus\Projects\QSort\main.cpp||In function 'int main()':|
C:\Users\Deus\Projects\QSort\main.cpp|49|error: no matching function for call to 'QSort(__gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >&, __gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >&)'|
||=== Build finished: 1 errors, 0 warnings ===|

似乎编译器无法解决T应该是什么。有没有办法做我想做的,或者我应该声明参数为类型T,并处理由此产生的不确定性?

It seems that the compiler is having trouble resolving what T should be. Is there a way to do what I'm trying to do, or should I just declare the arguments as type T, and work with the resulting uncertainty?

推荐答案

编译器无法从函数调用中推导出 T 。想想 std :: vector< T> :: iterator T * 时会发生什么:

The compiler has no way to deduce T from your function call. Think about what happens when std::vector<T>::iterator is T*:

int *b = ...;
int *e = ...;
QSort(b, e);

一般来说,如果你写 typename Something< TemplateParameter> :: anotherThing ,则无法在调用中推导出 TemplateParemter 。必须明确提供

In general, if you write typename Something<TemplateParameter>::anotherThing, then the TemplateParemter cannot be deduced in the call. It must be explicitly provided

QSort<int>(b, e);

我建议只使用 T 参数类型。这将允许你不仅接受向量迭代器,而且还接受 T * std :: deque< T> :: iterator 和任何其他随机访问迭代器。

I recommend to just use T as the parameter type. That will allow you to not only accept vector iterators, but also T*, or std::deque<T>::iterator and any other random access iterators.

这篇关于C ++模板不会接受迭代器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆