function template customization can solve specific template parameters and require specific function methods to achieve them.
Note that function template customization is the instantiation of the template, not the overload of the template;
When there are non-template functions (nontemplate function), non-template functions are preferred when the matching degree is the same.
such as comparison (compare) functions, Comparison of string (char*) type, can not be judged by the address to compare, should use the strcmp () function, need to customize the function template;
function template customization requires the use of "template<>", and an empty angle bracket indicates that the provided template argument supports all template parameters of the original version;
Code:
/* CppPrimer.cpp * * Created on:2013.12.9 * author:caroline//*eclipse CDT, gcc 4.8.1*/
#include <iostream> #include <vector> #include <cstring> using namespace std; Template <typename t> bool Compare (const t& T1, const t& T2) {std::cout << "I ver
Sion "<< Std::endl; Return (T1<T2)?
True:false; }//function template custom template<> bool Compare (const char* const &P1, const char* const &P2) {STD
:: cout << "third version" << Std::endl;
Return strcmp (P1, p2); }
There is a non-template priority to use non-template/*bool compare (const char* const &P1, const char* const &P2) {<span style= "White-space:pre
"> </span>std::cout <<" Forth version "<< Std::endl;
<span style= "White-space:pre" > </span>return strcmp (P1, p2); }*///handling literal type comparison template<unsigned N, unsigned m> bool Compare (const char (&P1) [N], const char (&
p2) [M]) {std::cout << "second version" << Std::endl;
Return strcmp (P1, p2);
int main (void) {const char* W ("Wendy");
Const char* C ("Caroline"); There is no function template customization to invoke the first version because the pointer cannot convert an array reference if (compare (c, W)) {std::cout << "Caroline is long." << St
D::endl;
else {std::cout << "Wendy is long." << Std::endl;
} if (Compare ("Caroline", "Wendy")) {std::cout << "Caroline is long." << Std::endl; else {std::cout << "Wendy is long.";< Std::endl;
return 0; }
Output:
Third version
Caroline is long.
Second version
Caroline is long.
Author: csdn Blog spike_king
More Wonderful content: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/cplus/