![](http://static.blog.csdn.net/images/category_icon.jpg)
版权声明:本文为博主原创文章,未经博主允许不得转载。
- #include "stdafx.h"
- #include "iostream"
- #include "string"
- using namespace std;
- //类模板,模板定义中class和typename是没有什么区别的
- //模板的声明和定义只能在全局、命名空间或者类范围内进行。
- template<class T1,class T2>
- class A
- {
- public:
- void f(T1 a, T2 b);
- };
- template<class T1,class T2> void A<T1,T2>::f(T1 a,T2 b)
- {
- cout << "class A------>T1:" << a <<";T2:" << b << endl;
- }
- //定义类模板的默认类型形参,默认类型形参不适用于函数模板。
- template<typename T3, typename T4=int>//T4是默认模板类型形参
- class B
- {
- private:
- T3 t3;
- T4 t4;
- public:
- B(T3 a, T4 b);
- void show();
- };
- template<class T3,class T4> B<T3,T4>::B(T3 a, T4 b):t3(a),t4(b){}
- //template<class T3,class T4=int> B<T3,T4>::B(T3 a, T4 b):t3(a),t4(b){},这样是错误的,
- //在类模板外部定义带有默认类型的形参时,在template的形参表中默认值应该省略
- template<class T3,class T4> void B<T3,T4>::show()
- {
- cout << "class B------>T3:" << t3 <<";T4:" << t4 << endl;
- }
- //非类型模板参数。
- //非类型形参只能是整型、指针和引用,像double,string,string **这样的类型是不允许的,但是double &,double *对象的引用或指针是正确的。
- template<class T5,int a>
- class C
- {
- private:
- T5 max[a];
- public:
- void cshow()
- {
- cout << "class C------>T5:" << typeid(T5).name()<< endl;
- }
- };
- int _tmain(int argc, _TCHAR* argv[])
- {
- //基本模板类测试
- A<int,int> a1;
- a1.f(2,3);
- A<int,char> a2;
- a2.f(2,'a');
- A<string,int> a3;
- a3.f("hello word!",5);
- //带有默认类型形参的模板类
- B<char,char> b1('a','b');
- b1.show();
- B<string,string> b2("你好","测试中......");
- b2.show();
- B<int,char> b3(25,'F');
- b3.show();
- //非类型模板参数
- const int i = 5;
- C<int,i> c1;
- c1.cshow();
- //int j = 5;
- //C<int,j> c2; //错误,调用非类型模板形参的实参必须是常量表达式
- C<char,i> c2;
- c2.cshow();
- return 0;
- }
执行结果: