模板
模板相当于把函数的变量类型在编译期间参数化,在编译阶段就已经决定mytype是什么类型了
template<class mytype>//mytype可以自己命名,经常命名为T
mytype myabs(mytype x){
if(x < 0){
return -x;
}
else{
return x;
}
}
例子
#include<iostream>
using namespace std;
template<class T>
T myabs(T a){
if(a < 0 ){
return -a;
}
else{
return a;
}
}
int main(){
cout <<myabs(-10.2)<<endl;
cout << myabs(-10)<<endl;
return 0;
}
扩展:
可以放入多个模板
template<class T1,class T2>
T1 myfuc(T1 a,T2 b){
...
return a;
}