#include<iostream>#include<cstring>#include<algorithm>usingnamespace std;template<typenameT>voidSwap(T& a, T& b){
T tmp = a;
a = b;
b = tmp;}intmain(){
string a ="dasdas", b ="lIDSA";// 以下两种写法均可Swap(a, b);// 自动推导数据类型 Swap<string>(a, b);// 手动指定数据类型
cout << a <<' '<< b << endl;return0;}
二、可以为类的成员函数创建模板,但不能是虚函数和析构函数
#include<iostream>#include<cstring>#include<algorithm>usingnamespace std;classCGirl{public:template<typenameT>CGirl(const T& data){
cout <<"data: "<< data << endl;}template<typenameT>voidshow(const T& data){
cout << data << endl;}// error: templates may not be 'virtual'/*
template <typename T>
virtual void vir_show(const T& data)
{
cout << data << endl;
}
*/};intmain(){
CGirl g("little turtle");
g.show("show show show");return0;}
#include<iostream>#include<cstring>#include<algorithm>usingnamespace std;template<typenameT>
T Add(const T& a,const T& b){return a + b;}intmain(){int a =19;char b ='x';// 当类型不匹配时,b是不会通过隐式类型转换转换成int的// 需要手动指定模板类型// 其实也很好理解,因为我们传入模板函数的参数有两种类型// 编译器不知道该将两种类型统一成哪一种类型// 尽管char可以转换成int,但是编译器没有这样做,毕竟是费力不讨好的事情int c =Add<int>(a, b);
cout << c << endl;return0;}
四、函数模板支持多个通用数据类型的参数
#include<iostream>#include<cstring>#include<algorithm>usingnamespace std;template<typenameT1,typenameT2>voidshow(const T1& a,const T2& b){
cout << a <<' '<< b << endl;}intmain(){int a =85;
string str ="lalallala";show(a, str);show(str, a);return0;}
五、函数模板支持重载,可以有非通用数据类型的参数
#include<iostream>#include<cstring>#include<algorithm>usingnamespace std;// show()有3个重载函数template<typenameT>voidshow(const T& a){
cout << a << endl;}template<typenameT1,typenameT2>voidshow(const T1& a,const T2& b){
cout << a <<' '<< b << endl;}// 这个重载函数中的第3个参数就是非通用数据类型template<typenameT1,typenameT2>voidshow(const T1& a,const T2& b,int c){
cout << a <<' '<< b <<' '<< c << endl;}intmain(){int a =85;
string str ="lalallala";show(a);show(str, a);show(str, str, a);return0;}