Instead of letting the type T
be determined from the second parameter, utilize the builtin typedefs in vector
to force T
to be determined from the first parameter and force the type of the second parameter to be determined from the first:
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
vector<string> my_vector = { "apples", "bananas", "peaches"};
bool vector_has_item1(vector<string> v, string value_to_check)
{
return std::find(v.begin(), v.end(), value_to_check) != v.end();
}
template <typename T>
bool vector_has_item2(vector<T> v, typename vector<T>::value_type value_to_check)
{
return std::find(v.begin(), v.end(), value_to_check) != v.end();
}
int main()
{
cout << vector_has_item1(my_vector, "bananas") << endl;
cout << vector_has_item2(my_vector, "bananas") << endl;
}