【C++】模板初阶
🍅讨厌废话,直接上车
☃️1.泛型编程
void Swap(int& left, int& right)
{
int temp = left;
left = right;
right = temp;
}
void Swap(double& left, double& right)
{
double temp = left;
left = right;
right = temp;
}
void Swap(char& left, char& right)
{
char temp = left;
left = right;
right = temp;
}
就问你写这么多交换函数烦不烦....
虽然函数重载很nice,但是架不住这么墨迹
做一个敏锐的程序员,识别出函数有很多相像的地方,然后写一个普适的模板(就像是活字印刷术的模板)
☃️2.函数模板
🐝2.1原理
函数模板代表了一个函数家族
该函数模板与类型无关
在使用时被参数化,根据实参类型产生函数的特定类型版本
格式:
template<typename T1, typename T2,......,typename Tn> 把<>里面的template换成class也可以的
返回值类型 函数名(参数列表){}
template<typename T>
void Swap(T& left, T& right)
{T temp = left;left = right;right = temp;
}
爽歪歪!!!!!!!!!!
当然也可以定义多个模板参数,用逗号分隔
template<class T, class Y>
T Add(T left, Y right)
{return left + right;
}
🐝2.2实例化
用不同类型的参数使用函数模板时,称为函数模板的实例化
template<class T, class Y>
T Add(T left, Y right)
{return left + right;
}
int main()
{Add(1, 2);return 0;
}
但是要注意原理
template<class T>
void Swap(T& X, T& Y)
{T tmp = X;X = Y;Y = tmp;
}
int main()
{int a = 1, b = 2;Swap(a, b);double c = 1.1, d = 2.2;Swap(c, d);
}
其实调用的并不是一个函数,只不过int double两个类型的Swap编译器帮我们写完了!
其实库函数中有个直接的交换函数 swap(a,b);
头文件#<iostream>中就包含了头文件#<algorithm>
模板参数实例化分为:隐式实例化和显式实例化。注意格式就好
☃️3.类模板
类模板是泛化的类,模板类是类模板的实例化
template<class T1, class T2, ..., class Tn>
class 类模板名
{
// 类内成员定义
};
🐝3.1原理
template<class T>
class Stack
{
public:Stack(int capacity = 4){_a = new T[capacity];}
private:T* _a;//..
};
int main()
{Stack<int>st1;Stack<double>st2;return 0;
}