前言
这篇文章主要是方便各位码友及我自己查阅使用。若希望获得更多详细信息,可前往devdocs网站。
用法
template
是模板函数,可以应对不知道类型的变量。
格式
template <class /*或typename*/ type>
/*type of the function*/ function_name(type pram) {
/*
* write down your code here
* ...
* ...
* return TypeOfTheFunction
* /
}
还可以根据需求改变函数类型和参数个数及参数类型。
附:template
函数可以容纳多种类型,还可以用作类和结构体的定义,比方说:
#include <iostream>
using namespace std;
template <class A, class B>
struct dataType {
A d1;
B d2;
};
template <class C, class D> // 当调用对于用template定义的类或者结构体时,函数也要用template
void out(dataType<C, D> d) {
cout << d.d1 << d.d2;
}
int main() {
dataType<int, string> da = {100, " years old!"};
out(da);
}
结果:
100 years old!
实践
之前不知道这个的时候,在自己的头文件里写print_vec()
的函数时,写了很多函数,其中每个参数的类型是vector<int> vec
,vector<double> vec
,vector<string> vec
等,非常不方便。
这是拿template
改进后的代码:
template <class T>
void print_vec(vector<T> v) {
for (auto i: v) cout << i << ' ';
cout << endl;
}
可见template
的用处及价值
用的时候:
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> vec{0, 1, 2, 3};
print_vec(vec);
}
结果:
0 1 2 3
总结
掌握好template
(模板函数)可以帮你节省下很多代码的工夫,但是有时候写出来可读性很低,因此在写代码的时候一定要用注释增加可读性,方便日后阅读。当然了,如果你愿意,也可以像我一样以个人随笔的方式发表出来。