[C++]模板template
2021/5/11 20:25:27
本文主要是介绍[C++]模板template,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
模板的使用
定义:
模板是泛型编程的基础,泛型编程即以一种独立于任何特定类型的方式编写代码。 模板是创建泛型类或函数的蓝图或公式。库容器,比如迭代器和算法,都是泛型编程的例子,它们都使用了模板的概念。 每个容器都有一个单一的定义,比如 向量,我们可以定义许多不同类型的向量,比如 vector <int> 或 vector <string>。
————From 菜鸟编程
语法:
template<class T> ...
这里语法看不懂没有关系
后面会有解释
函数模板
在函数上套上模板
可以满足处理不同数据类型的需要
比如 STL 中自带的 swap 函数
只能进行 int类型数据 的转化
要满足所有类型的转化 就要依靠模板
Code:
template<class T> T Swap(T &a,T &b){ T temp = a; a = b; b = temp; }
这里就假定了一个类 T
当输入的是 int 类型数据的时候
T 所表示的含义就是 int
就把所有的 T 视为 int 即可
输入的是其他类型的也一样
效果演示
Code
#include<bits/stdc++.h> using namespace std; template<class T> T Swap(T &a,T &b){ T temp = a; a = b; b = temp; } int main(){ int x1 = 1,y1 = 2; double x2 = 1.5,y2 = 2.4; Swap(x1,y1); cout << x1 << " " << y1 << endl; Swap(x2,y2); cout << x2 << " " << y2 << endl; return 0; }
Show
2 1 2.4 1.5 -------------------------------- Process exited after 0.05167 seconds with return value 0 请按任意键继续. . .
类模板
原理作用和函数模板相似
直接来看代码
(ps: 个人比较喜欢指针的写法 但会把非指针的代码放在折叠中)
Code:
#include<bits/stdc++.h> using namespace std; template<class T> class class1{ public: T a,b; T Max(){ if(a > b) return a; else return b; } }; int main(){ class1<int>x,*px = &x; cin >> px->a >> px->b; cout << px->Max() << endl; class1<double>y,*py = &y; cin >> py->a >> py->b; cout << py->Max() << endl; return 0; }
非指针
#include<bits/stdc++.h> using namespace std; template<class T> class class1{ public: T a,b; T Max(){ if(a > b) return a; else return b; } }; int main(){ class1<int>x; cin >> x.a >> x.b; cout << x.Max() << endl; class1<double>y; cin >> y.a >> y.b; cout << y.Max() << endl; return 0; }
Print:
10 20 20 10.6 10.5 10.6 -------------------------------- Process exited after 10.52 seconds with return value 0 请按任意键继续. . .
这篇关于[C++]模板template的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-15PingCAP 黄东旭参与 CCF 秀湖会议,共探开源教育未来
- 2024-05-13PingCAP 戴涛:构建面向未来的金融核心系统
- 2024-05-09flutter3.x_macos桌面os实战
- 2024-05-09Rust中的并发性:Sync 和 Send Traits
- 2024-05-08使用Ollama和OpenWebUI在CPU上玩转Meta Llama3-8B
- 2024-05-08完工标准(DoD)与验收条件(AC)究竟有什么不同?
- 2024-05-084万 star 的 NocoDB 在 sealos 上一键起,轻松把数据库编程智能表格
- 2024-05-08Mac 版Stable Diffusion WebUI的安装
- 2024-05-08解锁CodeGeeX智能问答中3项独有的隐藏技能
- 2024-05-08RAG算法优化+新增代码仓库支持,CodeGeeX的@repo功能效果提升