Reputation: 11
What I'm trying to do:
Write a specialized version of the template from the previous exercise to handle
vector<const char*>
and a program that uses this specialization.
I wrote the program like this:
template<typename T>
int count(vector<T> tvec, const T &t);
template<>
int count(vector<const char *> tvec, const char *const &s)
{
int count = 0;
for (auto c : tvec)
if (c == s) {
++count;
}
return count;
}
template<typename T>
int count(vector<T> tvec, const T &t)
{
int count = 0;
for (auto c : tvec)
if (c == t) {
++count;
}
return count;
}
cout << count(svec, "GUO");
but I get the error that says
deduced conflicting types for parameter ‘const T’ (‘std::basic_string<char>’ and ‘char [4]’)
I want to know how to handle this. and further, in the template function, it seems that an array can be changed to the pointer, why my program cannot handle it?
Upvotes: 1
Views: 3409
Reputation: 71989
Don't deduce on both parameters, it leads to conflicts. Write this:
template <typename T>
int count(const vector<T>& tvec, const typename vector<T>::value_type& t);
Also, consider overloading instead of specializing. Specializing a function template is pretty much never what you want.
Upvotes: 1
Reputation: 172934
Firstly, it seems svec
is defined as vector<string>
, maybe it should be vector<const char*>
;
Secondly, explictly define a var as const char*;
Try this:
vector<const char*> svec;
const char* chars = "GUO";
std::cout<<my_count(svec,chars);
BTW: A variable of type char array(char[]) can be used as type char pointer(char*), but they are different as type, and they are different as a template paremeter.
Upvotes: 0