The template role in C + + is to combine functions that are only of different types but functionally similar, but sometimes the functions in template do not satisfy all type invocations. As shown below:
Template <class kty>
inline int hash_wrap (const kty& k)
{return
(int) k;
}
all numeric types use the template without problems, but string types do not, because type conversions with string to int are not supported (during compilation). So we need to add a support for string outside the template, and the code is as follows:
Template <>
inline int hash_wrap<string> (conststring & k)
{return
k.size ();
}
Where template <> indicates that the function is an extension of the template type,<string> indicates that the string type of the original template is overwritten.
For example, the following two examples are as follows:
Example 1:
Template <class kty>
inline unsigned int get_size (const kty&k)
{return
sizeof (kty);
}
template <>
inline unsigned int get_size (conststring& k)
{return
k.length () + 1;
}
Example 2:
template <class kty> inline bool Cmp_key (const kty& K, constchar* dest) {retur
n k = = * (kty*) dest;; Template <> inline bool Cmp_key (const string& k,const char* dest) {return strcmp (K.c_str (), dest) = 0;}