带迭代器的模板函数
Template function with iterators
我一直在尝试在加速c++中执行Ex. 10-02,它给了我错误,我最终一直在"简化"我的程序,直到我达到这一点,甚至它仍然无法编译(通过g++)给我错误:
test.cpp: In function ‘int main()’:
test.cpp:22: error: no matching function for call to ‘dumb(__gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >, __gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >)’
这是我的程序:
#include <algorithm>
#include <iostream>
#include <vector>
using std::cout; using std::endl;
using std::vector;
template <class Ran, class T> T dumb(Ran begin, Ran end)
{
return *begin;
}
int main()
{
vector<int> myVector;
for (int i = 1; i <= 9; ++i)
myVector.push_back(i);
int d = dumb(myVector.begin(), myVector.end());
cout << "Value = " << d << endl;
return 0;
}
是什么导致这个错误?
编译器不能推断这里的返回类型。实际上,这里没有必要将返回类型设置为模板参数:
template <class Ran> typename Ran::value_type dumb(Ran begin, Ran end)
{
return *begin;
}
问题是你的函数原型:
template <class Ran, class T> T dumb(Ran begin, Ran end)
当使用template
s时,返回类型是依赖类型(这里是T
),不能隐式地推导。
所以你重新设计的功能应该是这样的:
template <class T, class Ran>
// ^^^^^ 'T' is coming before 'Ran'
T dumb(Ran begin, Ran end)
{
return *begin;
}
应该命名为
int d = dumb<int>(myVector.begin(), myVector.end());
^^^^
我们做了2个改动:
- 需要明确提及的类型(即
T=int
)为未来1 - 调用
dumb<>
时明确提到int
,因此返回类型是可扣除的
[注意:这个解决方案对于你的理解来说是非常通用的。正如@Bjorn的回答中提到的,对于vector<>
,类型可以使用::value_type
自动推断[/p>
相关文章:
- 如何在C++中将迭代器作为函数参数传递
- 如何在 c++ 中将字符串迭代器变量传递给函数?
- 为什么我的模板化函数需要从一个迭代器转换到另一个迭代器?
- 如何创建迭代器函数
- 为什么在指向对象的迭代器上调用函数不允许我更改对象本身?
- 迭代器库中的 std::size() 不适用于传递给函数的 C 样式数组
- 使用迭代器的模板类的构造函数
- C++:复制迭代器的构造函数
- 基于函数而不是集合的二分搜索或迭代器?
- 成员函数中的迭代器出现问题
- 使用迭代器的自定义比较器函数
- 专门C++使用指针值类型的通用迭代器的模板函数?
- 从 std::vector 迭代器中执行函数指针
- 调用 erase() 函数是否也会在擦除元素之前更改迭代器值?
- 如何基于循环迭代器选择函数
- 矢量迭代器在尝试调用函数时使我的程序崩溃
- 成员函数不能为集合迭代器和const_iterator的输入重载(但可以为其他 STL 迭代器重载)
- 具有C++迭代器参数的多功能函数
- C++如何获取传递给函数(STL 迭代器)的参数的名称
- C++ 解释重载成员函数迭代器(int i = 0) 的构造"one liner":i(i) { };