【C++】模板的使用
2022/7/22 2:00:14
本文主要是介绍【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; }
这篇关于【C++】模板的使用的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-01巧用 TiCDC Syncpoint 构建银行实时交易和准实时计算一体化架构
- 2024-05-01银行核心背后的落地工程体系丨Oracle - TiDB 数据迁移详解
- 2024-04-26高性能表格工具VTable总体构成-icode9专业技术文章分享
- 2024-04-16软路由代理问题, tg 无法代理问题-icode9专业技术文章分享
- 2024-04-16程序猿用什么锅-icode9专业技术文章分享
- 2024-04-16自建 NAS 的方案-icode9专业技术文章分享
- 2024-04-14ansible 在远程主机上执行脚本,并传入参数-icode9专业技术文章分享
- 2024-04-14ansible 在远程主机上执行脚本,并传入参数, 加上remote_src: yes 配置-icode9专业技术文章分享
- 2024-04-14ansible 检测远程主机的8080端口,如果关闭,则echo 进程已关闭-icode9专业技术文章分享
- 2024-04-14result 成功怎么写-icode9专业技术文章分享