我们在编程程序时,经常会遇到功能非常相似的模块,只是它们处理的数据不一样。但我们没有办法,只能分别写多个方法来处理不同的数据类型。这个时候,那么问题来了,有没有一种办法,用同一个方法来处理传入不同种类型参数的办法呢?泛型的出现就是专门来解决这个问题的。
比如说我现在需要处理某个点数据时。我们定义了两种描述点的结构体
struct PointXYZ{
float x;
float y;
float z;
}
struct PointXYZRGB{
float x;
float y;
float z;
float r;
float g;
float b;
}
而我们在调用某些函数,由于使用了PointXYZRGB结构体存储数据。但函数支持的传入参数的类型却是PointXYZ。这时我们有两种解决办法
1.将PointXYZRGB的值赋值给PointXYZ。然后再调用该函数。
2重新复制一个支持PointXYZRGB的函数
无疑,上述的两种办法都比较麻烦,在遇到这样的需求时,使用泛型则是一个较好的选择。
//template关键字用法
template <typename T>
void printXYZ(T point)
{
cout << point.x <<point.y<<point.z<<endl;
}
//定义两种结构体类型的变量
PointXYZ m_pointXYZ;
PointXYZRGB m_pointXYZRGB;
//使用同一个函数调用两种不同的类型的变量
printXYZ<PointXYZ> (m_pointXYZ);
printXYZ<PointXYZRGB> (m_pointXYZRGB);
以上代码介绍了template的用法
这里贴上使用template的例子,供各位同学更加清晰template的用法
#include <iostream>
using namespace std;
template <typename T>
void PrintfType(T iobj )
{
cout << typeid( iobj ).name();
}
int main() {
int m_int=0;
float m_float=0;
double m_double =0;
PrintfType(m_int);
PrintfType(m_float);
PrintfType(m_double);
}
上述为使用泛型函数时的用法,当在类中使用时写法为
#include <iostream>
using namespace std;
template <typename T>
class A {
public:
T m_type;
A(T value){
m_type =value;
};
void PrintType(void){
cout << typeid( m_type).name();
}
};
int main(){
//类与函数不同,他需要先声明T的类型
int m_int=1;
float m_float=2;
A<int> class1;
A<float> class2;
class1.PrintType();
class2.PrintType();
}
可以直接复制以上代码到C++编译器中使用