C++除了类里的内存模型比较有意思之外,泛型编程也是很有思想的抽象。当然最有用的还是标准模板库,带上标准的~里面包含了各种现成的容器,好用并且格式比较统一 美观~
模板函数
#include <iostream>
#include <string>
using namespace std;
template <typename Type>
const Type& GetMax(const Type& value1, const Type& value2){
if(value1 > value2)
return value1;
else
return value2;
}
int main(){
int num1 = -101, num2 = 2011;
int res = GetMax(num1, num2);
cout << "Max : " << res << endl;
return 0;
}
模板类
模板定义
模板实例化:使用一个或多个模板参数来创建特定的类型。
模板具体化:使用特定的类型实例化模板时,需要显示地指定不同的行为。为特点的类型指定行为。
#include <iostream>
using namespace std;
//模板定义
template <typename T1=int, typename T2=double>
class HoldsPair{
private:
T1 value1;
T2 value2;
public:
HoldsPair(const T1& val1, const T2& val2):value1(val1), value2(val2){}
const T1& GetFirstValue() const;
const T2& GetSecondValue() const;
}
//模板具体化
template<> class HoldsPair<int, int>
{
private:
int value1;
int value2;
string strFun;
public:
HoldsPair(const int& val1, const int& val2):value1(val1), value2(val2){}
const int& GetFirstValue() const{
cout << "Returning integer" << value1 << endl;
return value1;
}
};
int main(){
HoldsPair<int, int> pairIntInt(222, 333);
pairIntInt.GetFirstValue();
return 0;
}