模板技术:本质:把类型作参数
模板函数:
template <typename T1,typename T2> //还能用class代替typename T1 add(T1 num1,T2 num2) //这是一个模板函数 { cout<<"T1 add(T1 num1,T2 num2)"<<endl; return num1 + num2; } int main() { int a=1,b=2; float f1=3.2f,f2=4.9f; int res = add(a,f1); float res2 = add(f2,b); cout<<res<<endl<<res2<<endl; }
模板类:
template <typename T1,typename T2> class Student { public: Student() { cout << "Student()" << endl; this->name = " "; this->age = 0; } Student(const T1 &name,const T2 &age); void showStu()const; private: T1 name; T2 age; }; template <typename T1,typename T2> Student<T1,T2>::Student(const T1 &name,const T2 &age) { cout<<"Student::Student(const T1 &name,const T2 &age)"<<endl; this->name = name; this->age = age; } template <typename T1,typename T2> void Student<T1,T2>::showStu()const { cout<<"void Student::showStu()const"<<endl; cout<<this->name<<" "<<this->age<<endl;; } int main() { Student<string ,int> stu("zhangsan",22); stu.showStu(); Student<int,string> stu1(23,"lisi"); stu1.showStu(); }