我正在尝试实现一个简单的模板函数,这段代码不能编译,但我希望它会让你知道我正在尝试做什么:
template<typename T>
typename T::iterator do_find(const T& container, const int val)
{
return std::find(container.begin(), container.end(), val);
}
我想返回发现自己返回的迭代器,而不知道我在模板函数do_find中收到的容器类型。我做错了什么?
这是主要的:
int main()
{
std::vector<int> c;
c.push_back(42);
c.push_back(0);
c.push_back(1);
c.push_back(-58);
c.push_back(42);
c.push_back(777);
c.push_back(1911);
c.push_back(9);
do_find(c, 42);
return 0;
}
编译错误:
In file included from main.cpp:14:0:
find.hpp: In instantiation of ‘typename T::iterator do_find(const T&, int) [with T = std::vector<int>; typename T::iterator = __gnu_cxx::__normal_iterator<int*, std::vector<int> >]’:
main.cpp:29:16: required from here
find.hpp:17:59: error: could not convert ‘std::find<__gnu_cxx::__normal_iterator<const int*, std::vector<int> >, int>((& container)->std::vector<_Tp, _Alloc>::begin<int, std::allocator<int> >(), (& container)->std::vector<_Tp, _Alloc>::end<int, std::allocator<int> >(), (* & val))’ from ‘__gnu_cxx::__normal_iterator<const int*, std::vector<int> >’ to ‘std::vector<int>::iterator {aka __gnu_cxx::__normal_iterator<int*, std::vector<int> >}’
find.hpp: In function ‘typename T::iterator do_find(const T&, int) [with T = std::vector<int>; typename T::iterator = __gnu_cxx::__normal_iterator<int*, std::vector<int> >]’:
find.hpp:18:1: error: control reaches end of non-void function [-Werror=return-type]
cc1plus: all warnings being treated as errors
答案 0 :(得分:7)
如果您有const T& container
作为此功能的第一个参数,则必须返回typename T::const_iterator
。