函数模板
c++函数模板和模板函数的区别:
(1)、函数模板是模板的定义,定义中用到通用类型定义;
(2)、模板函数是实实在在的函数定义,它由编译系统调用函数时产生。
简单的示例代码:
#include<iostream>
#include<string>
#include<iomanip>
using namespace std;
const int lim=4;
//函数模板
template <typename AnyType>
void Swap(AnyType &a,AnyType &b){
AnyType temp;
temp=a;
a=b;
b=temp;
cout<<"引用内a="<<a<<endl;
cout<<"引用内b="<<b<<endl;
}
template <typename AnyType>
void Swap1(AnyType *a,AnyType *b){
AnyType *temp=NULL;
temp=a;
a=b;
b=temp;
cout<<"指针内a="<<*a<<endl;
cout<<"指针内b="<<*b<<endl;
}
template <typename AnyType>
void Swap2(AnyType a,AnyType b){
AnyType temp;
temp=a;
a=b;
b=temp;
}
template <typename AnyType>
void Swap3(const AnyType &a,const AnyType &b){//传入的引用保证了实参传入不发生改变
//AnyType temp;
//temp=a;
//a=b;
//b=temp;
}
template <typename AnyType>
void print(AnyType a,AnyType b){
cout<<setprecision(100)<<"a="<<a<<endl;
cout<<setprecision(100)<<"b="<<b<<endl;
}
//重载函数模板
template <typename T>
void Swap(T a[],T b[],int n){
T temp;
for(int i=0;i<n;i++){
temp=a[i];
a[i]=b[i];
b[i]=temp;
cout<<a[i]<<" ";
}
cout<<endl;
for(int i=0;i<n;i++){
cout<<b[i]<<" ";
}
}
int main(){
//传入整形
int a=12919;
int b=12331;
//没有交换
Swap3(a,b);
print(a,b);
Swap2(a,b);
print(a,b);
//交换
Swap(a,b);//引用 传入实参则发生改变
print(a,b);
//以指针传入函数 但是实参未发生改变
//a=12919,b=12331;
Swap1(&a,&b);//指针传值
print(a,b);
//传入字符串
string str1="1hsdjhs dshjfhsd sdf fs";
string str2="sdfhsj ncxbvn 121231323";
Swap1(&str1,&str2);//指针传值
print(str1,str2);
//输入double型
double nu1=3.435345345345345345345;
double nu2=1.345345734573845743534534534534;
Swap1(&nu1,&nu2);//指针传值
print(nu1,nu2);
//重载
int c[4]={231,12312,21312,213123};
int d[4]={54645,546,45645645,45645};
Swap(c,d,lim);
return 0;
}
(全文完)