//------------------------第六章 模板----------------------------------------------
/*
模板是实现代码重用机制的一种工具,可以实现类型参数化。模板分为函数模板和类模板。
C++中不建议使用宏,因为宏避开了类型检查机制,容易造成不必要的错误。
模板声明形式:
template <class Type> //class可以换成typename
返回类型 函数名(模板参数表)
{
函数体
}
*/
#include <iostream>
#include <cstring>
using namespace std;
template <typename Type>
Type GetMax(Type lhs, Type rhs)
{
return lhs > rhs ? lhs : rhs;
}
int main()
{
int nLhs = 10, nRhs = 90;
float fLhs = 10.2, fRhs = 21.2;
double dLhs = 2.11, dRhs = 0.123;
char cLhs = 'b', cRhs = 'a';
cout << GetMax(nLhs, nRhs) << endl
<< GetMax(fLhs, fRhs) << endl
<< GetMax(dLhs, dRhs) << endl
<< GetMax(cLhs, cRhs) << endl;
return 0;
}
#include <iostream>
#include <cstring>
using namespace std;
template <typename Type>
Type Sum(Type *pArray, int size = 0)
{
Type total = 0;
for (int i = 0; i < size; i++)
total += pArray[i];
return total;
}
int main()
{
int nArray[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
double dArray[] = {1.1, 2.2, 3.3, 4.4};
cout << Sum(nArray, 9) << endl;//output 45
cout << Sum(dArray, 4) << endl;//output 11
return 0;
}
#include <iostream>
#include <cstring>
using namespace std;
//template <typename T>与函数模板定义语句之间不允许有别的语句
//int i; //这里出错,不允许
//T sum(T in);
//不过可以同时多个类型
template <typename T1, typename T2>
void OutputData(T1 lhs, T2 rhs)
{
cout << lhs << " " << rhs << endl;
}
int main()
{
OutputData('a', "b");
OutputData(1, 2);
OutputData(1, 1.9);
return 0;
}
#include <iostream>
#include <cstring>
using namespace std;
template <typename T>
T Max(T lhs, T rhs)
{
return lhs > rhs ? lhs : rhs;
}
int Max(int lhs, int rhs)//课本上只写int Max(int, int);但不能通过,必须要有定义
{
return lhs > rhs ? lhs : rhs;
}
int main()
{
int i = 10;
char c = 'a';
Max(i, i);//正确调用
Max(c, c);//正确调用
//解决办法可以是再重载一个普通函数,不需要模板函数,并且要
//同名,加上int Max(int i, char c)就对了
cout << Max(i, c) << endl;//出错,原来是模板函数不会进行隐式强制类型转换
cout << Max(c, i) << endl;//出错,原来是模板函数不会进行隐式强制类型转换
return 0;
}
下面会继续更新---------------------------------------------------------------------------------------------------------------------