C++-泛型

  泛型是为了解决数据类型的通用性。
在定义函数或者类时先不定义类型,用一个占位符占下来,实例化时再赋予其类型。
一般分为两步:
1.指定一种通用类型T,不具体指明是哪一种类型。
2.实例化类时把T替换成int 、string、...内建或者是自定类型。

1.函数语法
 

//函数返回类型 函数名(形参列表…)
//返回的是 T1 输入是T1 T2 int
//template 是关键字

//下面两种写法可以
template  <typename T1,typename T2>
T1 fun(T1, T2, int){ }
template  <class T1, class T2>
T1 fun(T1, T2, int){ }

//下面两种写法不可以 会报T2未定义
template  <typename T1,T2>  
T1 fun(T1, T2, int){ }
template  <class T1, T2>  
T1 fun(T1, T2, int){ }


2.类语法
 

/*template  <class 模版参数列表…>
class 类名
{ //类体}
	成员的实现…
}*/

//1.定义了两个参数
template  <class T1, class T2 >
class fxClassA 
{
private:
	int a;
	T1 b;              //成员变量也可以用模板参数
public:
	int fun1(T1 x, int y);
	T2 fun2(T1 x, T2 y);
};

//2.类实现部分 每个函数上都要有类型定义
template  <class T1, class T2 >
int fxClassA<T1>::fun1(T1 x, int y) {}//这个函数没有用到T2,如果不写是会报错的
template  <class T1, class T2 >
T2 fxClassA<T1, T2>::fun2(T1 x, T2 y) {}
//3.类使用
int template_main() 
{
	//定义对象a,并用int替换T1, float替换T2
	fxClassA<int, float>  a;
	//实例化a,调用a的属性和方法……
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章