一、普通编程
#include <iostream>
using namespace std;
template<typename T>
bool GreaterThan(T a,T b)
{
if (a > b)
return true;
else
return false;
}
int main(void)
{
// double a = 6.4, b = 6.2;
string a = "linux", b = "harmonyOS";
cout << GreaterThan<string>(a, b) << endl;
getchar();
return 0;
}
二、模板特化编程
#include <iostream>
using namespace std;
template<typename T>
bool GreaterThan(T a,T b)
{
cout << "GreaterThan(T a,T b)" << endl;
if (a > b)
return true;
else
return false;
}
//对GreaterThan函数在string类型的特化,template<> 是特化标志
template<>
bool GreaterThan(string a, string b)
{
cout << "GreaterThan(string a, string b)" << endl;
if (a.size() > b.size())
return true;
else
return false;
}
bool GreaterThan(string a, string b)
{
cout << "普通函数" << endl;
if (a.size() > b.size())
return true;
else
return false;
}
int main(void)
{
// double a = 6.4, b = 6.2;
string a = "linux", b = "harmonyOS";
//如果没有指定执行的是模板函数,那么普通函数执行的优先级最高,之后是特化的模板
cout << GreaterThan(a, b) << endl;
// cout << GreaterThan<sting>(a, b) << endl;
getchar();
return 0;
}
三、总结
(1)模板特化类似于函数重载,而且都是编译时确定,而不是运行时确定。
(2)特化、specialize,就是让模板参数T在一个特定类型时可以特殊处理。
(3)特化声明一般时template<>