1、函数模板基本语法
#include<iostream>
#include<cmath>
#include<cstring>
#include<stdio.h>
#include<stdlib.h>
#include<vector>
using namespace std;
template<typename T> //声明一个模板,告诉编译器后面代码中紧跟着的T不要报错,T是一个通用数据类型
void Swap(T &a,T &b)
{
T temp=a;
a=b;
b=temp;
}
int main()
{
int a,b;
cin>>a>>b;
Swap(a,b);
cout<<a<<" "<<b<<endl;
string x,y;
cin>>x>>y;
Swap(x,y);
cout<<x<<" "<<y<<endl;
return 0;
}
定义方法:template<typename T>或template<class T> //只对接下来那一个函数有用
两种使用方法:自动类型推导、显示指定类型
Swap(a,b)和Swap<int>(a,b)
注意事项:使用函数模板必须要确定数据类型,而且该数据类型要唯一
2、普通函数和函数模板的区别
- 普通函数调用可以发生隐式类型转换
- 函数模板 用自动类型推导,不可以发生隐式类型转换
- 函数模板 用显示指定类型,可以发生隐式类型转换
#include<iostream>
#include<cmath>
#include<cstring>
#include<stdio.h>
#include<stdlib.h>
#include<vector>
using namespace std;
int Add(int a,int b)
{
return a+b;
}
template<typename T> //声明一个模板,告诉编译器后面代码中紧跟着的T不要报错,T是一个通用数据类型
T Add2(T a,T b)
{
return a+b;
}
template<typename T> //声明一个模板,告诉编译器后面代码中紧跟着的T不要报错,T是一个通用数据类型
T Add3(T a,T b)
{
return a+b;
}
int main()
{
int a=10;
int b=20;
char c='c';
cout<<Add(a,c)<<endl;
cout<<Add2(a,b)<<endl;
//cout<<Add2(a,c)<<endl;//错误,不可以隐式类型转换
cout<<Add3<int>(a,c)<<endl;
return 0;
}
3、普通函数和函数模板调用规则
- 如果二者都可以调用,有限调用普通函数
- 可以通过空模板参数列表来强制调用函数模板
- 函数模板也可以发生重载
- 如果函数模板可以产生更好的匹配,优先调用函数模板
#include<iostream>
#include<cmath>
#include<cstring>
#include<stdio.h>
#include<stdlib.h>
#include<vector>
using namespace std;
int func(int a)
{
cout<<"普通函数"<<endl;
}
template<typename T> //声明一个模板,告诉编译器后面代码中紧跟着的T不要报错,T是一个通用数据类型
T func(T a)
{
cout<<"函数模板"<<endl;
}
template<typename T> //声明一个模板,告诉编译器后面代码中紧跟着的T不要报错,T是一个通用数据类型
T func(T a,T b)
{
cout<<"重载函数模板"<<endl;
}
int main()
{
int a=10,b=20;
char c='c';
func(a);
func<>(a);
func(a,b);
func(c);
return 0;
}
4、模板的局限性
有自定义类型的时候可能会出问题
解决办法:运算符重载或者利用具体化模板
#include<iostream>
#include<cmath>
#include<cstring>
#include<stdio.h>
#include<stdlib.h>
#include<vector>
using namespace std;
class Person
{
public:
Person(string name,int age)
{
this->name=name;
this->age=age;
}
string name;
int age;
};
template<typename T> //声明一个模板,告诉编译器后面代码中紧跟着的T不要报错,T是一个通用数据类型
bool func(T &a,T &b)
{
if(a==b)
{
return true;
}
else
{
return false;
}
}
template<> bool func(Person &a,Person &b)
{
if(a.name==b.name && a.age==b.age)
{
return true;
}
else
{
return false;
}
}
int main()
{
Person a("TOM",10);
Person b("TOM",10);
bool ret=func(a,b);
//cout<<(a,b)<<endl;
if(ret)
cout<<"相等"<<endl;
else
cout<<"不相等"<<endl;
return 0;
}