带有迭代器的模板函数
我一直在努力做Ex。 Accelerated C++ 中的 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;
}
是什么导致了这个错误?
I've been trying to do Ex. 10-02 in Accelerated C++, and it was giving me errors and I eventually kept "simplifying" my program until I got to this point, and even still it wouldn't compile (via g++) giving me the error:
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> > >)’
Here's my program:
#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;
}
What's causing this error?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
编译器无法推断此处的返回类型。实际上,这里不需要将返回类型设置为模板参数:
The compiler cannot infer the return-type here. Actually there is no need to make the return-type a template-parameter here:
问题在于函数的原型:
使用
模板
时,返回类型是依赖类型(此处为T
),无法隐式推导 。所以你重新设计的函数应该是这样的:
并且它应该被称为,
所以我们做了 2 个更改:
T=int
)是第一个
dumb<>
并明确提及int
,所以返回类型是可推导的
[注意:这个解决方案对于您的理解来说非常通用。正如 @Bjorn 的回答中提到的,对于
vector<>
,可以使用::value_type
自动推导出类型。]The problem is the prototype of your function:
When using
template
s, return type which is dependent type (hereT
), cannot be deduced implicitly.So your re-designed function should be like this:
and it should be called as,
So we have done 2 changes:
T=int
) iscoming 1st
dumb<>
with explicit mention ofint
, sothat return type is deducible
[Note: This solution is very generic for your understanding. As mentioned in @Bjorn's answer, for
vector<>
the type can be deduced automatically using::value_type
.]