前言:在c++的学习中,模板是一个非常重要的知识点,虽然自己编程时很少去写的函数模板,类模板,但是在以后工作的时候,要经常去使用阅读别人写好的模板,而且要是以后要去看stl源码的话,理解c++经常使用的类是如何实现的,那对模板这一块的知识必须要有足够的了解。
函数模板
1.函数模板的语法
在一个函数之前写上
template <typename T>
void test1(){
}
但是我发现写成下面这样也没问题
template <class T>//参数T可以不止一个
void test1(){
}
2.函数模板编程练习——实现sort排序,swap函数,打印数组
#include <iostream>
#include <cstdlib>
using namespace std;
template<class T>
T mySwap(T &a ,T &b){
T temp = a;
a = b;
b = temp;
}
//利用选择排序,对int和char进行排序
template<class T>
void mySort(T *arr,int len){
for(int i = 0;i < len;i++){
for(int j = i+1;j < len;j++){
if(arr[i] > arr[j]){
mySwap<T>(arr[i],arr[j]);
}
}
}
}
template<class T>
void Print(T *arr,T len){
for(int i = 0;i<len;i++)
cout<<arr[i]<<endl;
}
void test01(){
char arr[] = {
1,2,2,3,4,5,7,8