c++中类模板(class template)简单示例

#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;
}


执行结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值