函数的模板:不知道函数模板是什么意思看,看了模板二字基本知道函数模板了,估计也就是一函数重复使用意思,只是传不同类似的参数然后返回对应类型的数据。
函数模板定义的形式:template<class T>或template <typenameT>
#include <iostream>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
using namespace std;
int main(int argc, char** argv) {
cout <<max(2,5)<<"\t"<<max(2.0,5.0)<<"\t"<<max('w','a')<<"\t"<<max("ABC","ABD")<<endl;
return 0;
}
template <class T>
T max(T m1,T m2)
{
return(m1>m2)?m1:m2;
}
//第二个例子
#include <iostream>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
using namespace std;
template <typename T>
void Swap(T &a,T &b);
int main(int argc, char** argv) {
int i = 10;
int j = 20;
cout <<"i,j=="<<i<<","<<j<<".\n";
Swap(i,j);
cout <<"i,j=="<<i<<","<<j<<".\n";
return 0;
}
template <typename T>
void Swap(T &a,T &b)
{
T temp;
temp=a;
a=b;
b=temp;
}
以上例子中第一个例子有点问题,今天测试中发现第一个例子没有申明自己的模板,直接定义模板了但是编译的时候不会报错也能顺利通过,但是其他模板不声明就不能编译通过,最后发现自己的max函数和标准库的max重名了,调用的时候调用的是标准库中的函数,所以能顺利编译通过以下是我改名后我的函数,需要添加声明的,所以在第一个例子的基础上修改一下贴出来以后留着查看
正确的例子:
#include <iostream>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
using namespace std;
//添加声明
template <class Person>
Person comparMax(Person m1,Person m2);
int main(int argc, char** argv) {
cout <<comparMax(2,5)<<"\t"<<comparMax(2.0,5.0)<<"\t"<<comparMax('w','a')<<"\t"<<comparMax("ABC","ABD")<<endl;
return 0;
}
template <class Person>
Person comparMax(Person m1,Person m2)
{
return(m1>m2)?m1:m2;
}