C++ 函数模板和类模板
结合实例,讲解下C++ 函数模板和类模板。
函数模板
1.通用表达式(定义函数模板):
template<typename T1, typename T2>返回类型 函数名(参数列表){函数体}
2.实例化
函数名,如:
//函数模板1
template <typename T>
int MaxNum(const T &v1, const T &v2) //返回最大数
{
if (v1 < v2)
return v2;
else
return v1;
}
//函数模板2
template <typename T>
T MixNum(const T &v1, const T &v2) //返回最小数
{
return (v1 < v2) ? v1 : v2;
}
//主函数
int main()
{
cout << MaxNum(3, 5) <<endl;
cout << MaxNum<int>(3, 5) << endl;
cout << MixNum(3.1, 5.0) << endl;
cout << MixNum<double>(3.1, 5.0) << endl;
return 0;
}
以上两种使用方法:
cout << MaxNum(3, 5) <<endl; //编译器自动设置参数类型
cout << MaxNum<int>(3, 5) << endl; //手动设置参数类型
运行结果:
5
5
3.1
3.1
类模板
//定义一个类模板myclass
template<class t1, class t2> class myclass
{
public:
myclass(){ cout << "构造函数" << endl; }
~myclass(){ cout << "析构函数" << endl; }
t1 show(t1 x, t2 y) {
cout << "show 函数:" << x << "\t" << "t2 is " << y << endl;
return 0;
}
private:
};
//主函数
int main()
{
myclass<int, string> test;
test.show(10, "hello");
return 0;
}
运行结果:
构造函数
show 函数:10 t2 is hello
析构函数