Reputation: 31
I want to define a helper function that takes a template parameter. I have tried making a templated function for this, but it does not compile. Any idea what I'm doing wrong? Here's the code I tried.
// vectors are great, but lack a find method. Implement one as a helper.
template<class T> bool vec_find(vector<T> &v, T obj)
{
vector<T>::iterator s;
for (s = v.begin(); s < v.end(); s++)
{
if (*s == obj)
{
return true;
}
}
return false;
}
Upvotes: 1
Views: 254
Reputation: 254431
Presumably, your compiler told you what the problem was. Mine said:
test.cpp:7:5: error: need ‘typename’ before ‘std::vector<T>::iterator’ because ‘std::vector<T>’ is a dependent scope
So to fix it, add typename
before vector<T>::iterator
:
typename vector<T>::iterator s;
^^^^^^^^
In general, you need that whenever the scope of a type name depends on a template parameter; until the template is instantiated, the compiler doesn't know how vector<T>
will be defined, and so needs to be told that a name scoped inside it refers to a type rather than something else.
However, there is a good reason why vector
doesn't have a find
method: the C++ library separates containers from the algorithms that act on them, so that any algorithm can act on any suitable sequence. You want to use std::find
for this:
return std::find(v.begin(), v.end(), obj) != v.end();
Upvotes: 1