对于代码相似的函数,我们可以使用函数模板。
类似的,对于那些代码相似的类,我们也可以使用类模板。
修改代码,首先声明一个类模板AAA。
- template<typename T>
- class AAA {
- private:
- T t;
- public:
- void test_func(const T &t);
- void print(void);
- };
这个类模板中有一个私有成员t,它的数据类型由传入的模板参数T决定。
还有两个公有的成员函数test_func和print。
分别实现这两个函数。
test_func函数
设置私有成员t的值。
- template
- void AAA
::test_func(const T &t) - {
- this->t = t;
- }
print函数
输出私有成员t的值。
- template
- void AAA
::print(void) - {
- cout << this->t << endl;
- }
在main函数中分别定义两个类,T分别是int和double。
main函数
- int main(int argc, char **argv)
- {
- AAA<int> a;
-
- a.test_func(1);
- a.print();
-
- AAA<double> b;
-
- b.test_func(1.23);
- b.print();
-
- return 0;
- }
编译测试,可以看到使用了AAA模板成功创建了两个对象。

类模板的使用可以分为两种:
上面的测试代码,使用的就是用到时再实例化。
在main函数中,只有使用 AAA
也可以在使用前,事先实例化。
即先使用:
template AAA<int>;
再使用:
AAA<int> a;
(事先实例化部分存疑,可能是我的理解有误,在代码中添加 template AAA

重载/定做类模板C++可以重载函数,类似的,也可以重载类模板,也叫作定做类模板。
修改代码,重载类模板AAA。
注意只是重载了T为int时的类模板,T为其他类型时模板还是会使用原来的AAA。
- template <>
- class AAA<int> {
- public:
- void test_func_int(const int & t)
- {
- cout << t << endl;
- }
-
- void print_int(void);
- };
-
- void AAA<int>::print_int(void)
- {
- cout << "for test" << endl;
- }
main函数
- int main(int argc, char **argv)
- {
- AAA<int> a;
-
- a.test_func_int(1);
- a.print_int();
-
- AAA<double> b;
-
- b.test_func(1.23);
- b.print();
-
- return 0;
- }
编译测试如下,可以看到T为int时,重载了类模板AAA,T为double时,没有影响。
