【C++】模板的使用
#include <iostream> using namespace std; struct job { char name[40]; double salary; int floor; }; void show(job &j); template <typename T> void Swap(T &a,T &b); const int LIM = 8; void show(int arr[],int n); template <typename T> void Swap(T a[],T b[],int n); template <> void Swap<job>(job &j1,job &j2); void Swap(int a,int b); int main() { int i = 10; int j = 20; cout <<"i,j = " << i << "," << j << "." <<endl; Swap(i,j); cout <<"After Swap,now i,j = " << "i,j = " << i << "," << j << "." <<endl; double x = 24.5; double y = 81.7; cout << "x,y = " << x << "," << y << "." << endl; Swap(x,y); cout <<"After Swap,now x,y = " << "x,y = " << x << "," << y << "." <<endl; int d1[LIM] = {0,7,0,4,1,7,7,6}; int d2[LIM] = {0,7,2,0,1,9,6,9}; cout << "Origianl arrays: " << endl; show(d1,LIM); show(d2,LIM); Swap(d1,d2,LIM); cout << "Swapped arrays: " << endl; show(d1,LIM); show(d2,LIM); job Rick = {"Rick",1000,10}; job Jack = {"Jack",1100,11}; show(Rick); show(Jack); Swap(Rick,Jack); cout << "After swap: " << endl; show(Rick); show(Jack); return 0; } template <typename T> void Swap(T &a,T &b) { T temp; temp = a; a = b; b = temp; } template <typename T> void Swap(T a[],T b[],int n) { T temp; for(int i = 0; i < n; i++) { temp = a[i]; a[i] = b[i]; b[i] = temp; } }
//显示具体化模板,只有形参为job结构体,才发挥作用 template <> void Swap<job>(job &j1,job &j2) { double t1; double t2; t1 = j1.salary; j1.salary = j2.salary; j2.salary = t1; t2 = j1.floor; j1.floor = j2.floor; j2.floor = t2; } void Swap(int a,int b) { int temp; temp = a; a = b; b = temp; cout << "this is function not template,a=" << a << ",b=" << b << endl; } //普通函数优先级高于显示模板,高于普通模板,相同参数,优先匹配普通函数 void show(int arr[],int n) { for(int i=0;i < n;i++) { cout << arr[i] <<" "; } cout << endl; } void show(job &j) { cout << j.name << ": " << j.salary <<"on floor" << j.floor << endl; }