基本应用
在已知类型的情况下,编译器可以进行数据类型的自动推导,如下例代码,但如果编译器无法自动推导的情况,则不能简单的写 toSwap(a, b);,而是需要在调用时声明类型,如: toSwap
#include <iostream>using namespace std;template<typename T>//声明T为模板类型,使编译器不报错,typename修改成class也是一样的void toSwap(T& a,T& b){T temp = a;a = b;b = temp;}int main(){int a = 1;int b = 2;toSwap(a, b);cout << "a="<<a<< endl;cout << "b="<<b<< endl;double c = 1.1;double d = 2.2;toSwap(c, d);cout << "c="<<c<< endl;cout << "d="<<d<< endl;return 0;}
a=2 b=1 c=2.2 d=1.1
普通函数和函数模板同名的调用规则
template
void toSwap(int& a,int& b){ int temp = a; a = b; b = temp; }
int main() { int a = 1; int b = 2;
toSwap(a, b);//调用普通函数toSwap<>(a, b);//调用模板函数char c = 'c';char d = 'd';toSwap(c, d);//虽然两个方法都可以执行,普通函数需要强制转化为int,模板函数更匹配,故而会调用模板函数return 0;
}
<a name="VwMQ3"></a>### 模板函数的局限性比如比较大小时,虽然类型推断可以做到,但并不是每个数据类型都支持运算符(当然我们也可以通过重载运算符让这个类支持),那么就需要用以下的模板重载的方式来解决:```c#include <iostream>#include <string>using namespace std;template<typename T>bool toCompare(T& a,T& b){return a > b;}class People{public:string name;int age;};//重载模板对People这个类的支持template<> bool toCompare(People& a,People& b){return a.age > b.age;}int main(){int a = 1;int b = 2;cout << toCompare(a,b) << endl;People p{"小明", 20};People p2{"小红", 30};cout << toCompare(p, p2) << endl;return 0;}
