If you have const T& container
as your first parameter to this function, you have to return typename T::const_iterator
instead.
Return an iterator inside a template
Pergunta
I'm trying to implement a simple template function, this code doesn't compile but I hope it will give you an idea about what I'm trying to do :
template<typename T>
typename T::iterator do_find(const T& container, const int val)
{
return std::find(container.begin(), container.end(), val);
}
I want to return the iterator that find itself returns, without knowing what type of container I receive in my template function do_find. What am I doing wrong ?
Here's the main :
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;
}
And the compiler error :
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
Solução
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow