对于C++初学者而言,使用类模板的一个最明显的好处就是它能给程序开发提供很大的方便。因为类模板与类型无关,所以模板类中的代码可以重复使用。接下来列举一个比较简单,只打印信息的类模板:
1.在类体内定义成员函数开发类模板
#ifndef HEAD_H_
#define HEAD_H_
#include<iostream>
#include<typeinfo>
template<typename Type>//声明类模板
class TestTemplateClass {
private:
Type value1;
Type value2;
public:
TestTemplateClass(Type x, Type y) { value1 = x; value2 = y; }
void printValue()const {
std::cout << "打印" << typeid(value1).name() << "类型数据" << std::endl;
std::cout << "value1 = " << value1 << std::endl
<< "value2 = " << value2 << std::endl << std::endl;
}
};
#endif
在声明类模板前应用template关键字,目的是让编译器知道我接下来定义的是一个类模板,然后在template后加入一对尖括号<>,在尖括号声明通用变量名称可加关键字class,也可用另一个关键字typename,两者是一样的。也就是说
template<typename Type>
和
template<class Type>
是等价的。这里使用class关键字并不是说Type必须是类,而只是说明变量Type是一个通用的类型说明符。
2.在类体外定义成员函数开发类模板
如果在类体外定义成员函数,需要在每一个属于该类模板的成员函数前加上模板类的开头代码(也就是template<typename ...>或template<class ...>),并在类名后面加上<Type>(Type为通用类型说明符),用代码的形式表示即为:
template<typename Type>
TestTemplateClass<Type>::TestTemplateClass(Type x, Type y){
//...
}
template<typename Type>
void TestTemplateClass<Type>::printValue()const {
//...
}
将模板类的成员函数定义放在头文件中,得到了另一个版本。即:
#ifndef HEAD_H_
#define HEAD_H_
#include<iostream>
#include<typeinfo>
template<typename Type>//声明类模板
class TestTemplateClass {
private:
Type value1;
Type value2;
public:
TestTemplateClass(Type x, Type y);
void printValue()const;
};
template<typename Type>
TestTemplateClass<Type>::TestTemplateClass(Type x, Type y) {
value1 = x;
value2 = y;
}
template<typename Type>
void TestTemplateClass<Type>::printValue()const {
std::cout << "打印" << typeid(value1).name() << "类型数据" << std::endl;
std::cout << "value1 = " << value1 << std::endl
<< "value2 = " << value2 << std::endl << std::endl;
}
#endif
接下来测试一下这个模板:
#include"head.h"
int main() {
TestTemplateClass<int> testInt(3, 2);
TestTemplateClass<double> testDouble(2.71, 3.14);
TestTemplateClass<char> testChar('f', 'h');
testInt.printValue();
testDouble.printValue();
testChar.printValue();
return 0;
}
结果为:
打印int类型数据
value1 = 3
value2 = 2
打印double类型数据
value1 = 2.71
value2 = 3.14
打印char类型数据
value1 = f
value2 = h
请按任意键继续. . .