【理論待補充...】
下面是一個函數模板特化的例子;
/// 模版特化
template <class T>
int compare(const T left, const T right)
{
std::cout << "in template<class T>..." << std::endl;
if (left < right) return -1;
if (left > right) return 1;
return 0;
}
// 這個是一個特化的函數模版
template < >
int compare(const char* left, const char* right)
{
std::cout << "in special template< >..." << std::endl;
return strcmp(left, right);
}
// 特化的函數模版, 兩個特化的模版本質相同, 因此編譯器會報錯
// error: redefinition of 'int compare(T, T) [with T = const char*]'|
//template < >
//int compare<const char*>(const char* left, const char* right)
//{
// std::cout << "in special template< >..." << std::endl;
//
// return strcmp(left, right);
//}
int main()
{
cout << compare(1, 4) << endl;
const char *left = "bello";
const char *right = "aorld";
cout << compare(left, right) << endl;
return 0;
}
參考:https://blog.csdn.net/gatieme/article/details/50953564