一、模板简介
在C++中,模板让程序员能够定义一种适用于不同类型的对象行为。这听起来有点像宏,但宏不是类型安全的,而模板是类型安全的。
二、模板声明语法
关键字template标志着模板类声明的开始,接下来是模板参数列表。该参数列表包含关键字typename,它定义了模板参数objectType, objectType是一个占位符,针对对象实例化模板时,将使用对象类型来替换它。
1、模板函数
如下是一个MAX模板函数:
template<typename objectType>
const objectType &GetMax(const objectType &value1, const objectType &value2) {
if (value1 > value2)
return value1;
else
return value2;
}
//调用模板的方法如下:
int Integer1 = 25;
int Integer2 = 30;
//注意这里调用GetMax时使用了<int>,这是将参数模板的objectType指定为int;
int MaxValue = GetMax<int>(Integer1, Integer2);
//然而实际上编译器很聪明,模板函数会自动推断其类型,所以下面的声明也是OK的.
int MaxValue = GetMax(Integer1, Integer2);
2、模板类
类是一种编程单元,封装的类的属性以及使用这些属性的方法。属性通常是私有成员,类是设计蓝图,其实际表示为对象。模板类是模板化的C++类,是蓝图的蓝图。使用模板类时,可指定要为哪种类型具体化类。
下面是一个简单的模板类,只有一个模板参数T:
template<typename T>//只有一个模板参数
class MyFirstTemplateClass {
public:
void SetValue(const T &newValue) { Value = newValue; }
const T &GetValue() const { return Value; }
private:
T Value;
};
#include <iostream>
using namespace std;
int main() {
//MyFirstTemplateClass用于保存一个类型为T的变量,该变量的类型是在使用模板时指定的。
//下面是该模板类的一种用法:
MyFirstTemplateClass<int> HoldInteger;//模板的实例化
HoldInteger.SetValue(5);
cout << "The value stored is:" << HoldInteger.GetValue() << endl;
//字符型
MyFirstTemplateClass<char*> HoldString;
HoldString.SetValue("Hello String!");
cout << "The value stored is:" << HoldString.GetValue() << endl;
}
声明多个参数:
template<typename T1, typename T2>
class Holdpair
{
private:
T1 Value1;
T2 Value2;
public:
Holdpair(const T1& value1, const T2& value2){
Value1=value1;
Value2=value2;
}
const T1& GetFirstValue() const
{
return Value1;
};
const T2& GetSecondValue() const
{
return Value2;
};
};