I have a template class that otherwise works perfectly, except I need to overload the insert method in case type T is a string.
template <class T>
class hashtable{
public:
void insert(T item){
/* Do Stuff */
};
template<> void insert(string item){
/* Do different stuff */
};
}
This is throwing error C2912: explicit specialization; 'void hashtable::insert(std::string)' is not a specialization of a function template.
I'm not sure what I'm doing wrong, or how I can fix this. All I need is a way to call the insert function differently depending on if T is a string or not.
You do not need to add the
template
word at all. You just overload the template function.Beware, though, regardless of the design you can get in trouble when you try to
insert
the types which are implicitly convertible to std::string, includingconst std::string &
andconst char*
. Believe it or not, in C++03 std::string had even implicit constructor fromint
!That is why people usually prefer to templetize the hashtable class, not the function.