解释C++的模板
书本解释:
c++的模板是泛型编程的基础,它使的开发者可以使用一种与具体类型无关的方式来编写代码。模板相当于创建泛型类或泛型函数的一套公式。程序库中有很多容器,例如迭代器与算法都用到了泛型机制,他们采用模板来开发。
每一种容器都只有一个定义,但是它所能容纳的元素类型却可以有很多种,例如可以声明vector
(1)模板函数的实现
编写一个返回两数中较大值的模板函数
#include
#include
using namespace std;
template
inline T const&Max(T const& a,T const& b)//模板函数的实现
{
return a}
int main() double f1=23.3; string s1="hello"; return 0; (2)模板类的实现
{
int i=49;
int j=10;
cout<<"Max(i,j):"<
double f2=45.3;
cout<<"Max(f1,f2):"<
string s2="world";
cout<<"Max(s1,s2):"<
}