【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; }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现