者:andy

关于C++Template的理解:

C++Template包含函数模板和类模板两种,顾名思义这两种的不同点在于所使用的场合不同,函数模板针对于函数使用,而类模板则针对于类使用.

使用类模板有什么优势呢?现在你要写一个求最大数的方法,你考虑到了N种情况(求两个整数,求两个浮点数,求两个字符,求...),这时候你可能会写N个重载方法,当你缴尽脑汁把一切可能发生的事情都想到的时候这个程序写完了,代码量是很多的,这时候解决这个问题的一个好的办法就是使用C++的模板,我们可以定义一个函数模板,这个模板接收任意类型的参数,编译器会根据你所传入的参数类型编译成对应类型的函数,及对应类型的返回值.

模板,在我的理解中就是定义一个公共的需求,比如这个word文档的模板,定义了大家都有可能用到的样式,C++的模板也就是让你定义一个公共的模块,把一些类似的功能的模块归类为一个模板,使用模板到底有什么好处呢?我觉的可以提高程序的重用性,减少代码的冗余及代码量.

个人意见,仅供参考

这些示例在Eclipse中都是可以正确运行的,让我们共同来学习^_^.

C ++template的定义:

传统意义上的template主要是提供了功能抽象,适用于多种类型具有相同或者相似的功能的场合,是一种范性设计理念。

Code Demo:
1.define function template
#include <iostream>
using namespace std;
//函数模板提供了一类函数的抽象,它以任意类型T为参数及函数返回值
template <class T> T max(T a,T b)//define a function template
{
return a>b?a:b;
}
char *max(char *a,char *b)// the method is template function overload
{
int flag=strcmp(a,b);
if(flag>0)
{
return a;
}
else
{
return b;
}
}
int main()
{
cout << max(2,5) << endl;
cout << max("gggg","fff") << endl;
return 0;
}
2.define class template
#include <iostream>
using namespace std;
template<class T> class family
{
private:
int a;
int b;
public:
int show(int);
void test();

};
template <class T> void family<T>::test()
{
cout << "this is a test method";
cout << show(10);
}
template <class T> int family<T>::show(int i)
{
return i*10;
}
family<class T> Person;
int main()
{
Person.test();
return 0;
} 
类模板的示例:
#include <iostream>
using namespace std;
template <class T> class Array
{
T *set;
int n;
public:Array(T *data,int i)
{
set=data;
n=i;
}
~Array(){}
void sort();//排序
int seek(T key);//检索
T sum();//求和
};
template<class T> void Array<T>::sort()
{
int i,j;
T d;
for(i=1;i<n;i++)
{
for(j=n-1;j>=i;j--)
{
if(set[j-1]>set[j])
{
d=set[j-1];
set[j-1]=set[j];
set[j]=d;
}
}
}
}
template <class T> int Array<T>::seek(T key)
{
for(int i=0;i<n;i++)
{
if(set[i]==key)
{
return i;
}
}
return -1;//表示没有找到
}
template <class T> T Array<T>::sum()
{
T s=0;
for(int i=0;i<n;i++)
{
s+=set[i];
}
return s;
}
int main()
{
int num[10]={1,2,5,3,7,9,23,4,10,19};
Array<int> myArray(num,10);
myArray.sort();
for(int i=0;i<10;i++)
{
cout << num[i] << " " <<endl;
}
cout << "n" << myArray.seek(5) << endl;
cout << "n" << myArray.sum() << endl;
return 0;
}
类模板之间继承关系的示例:
#include <iostream>
using namespace std;
template <class TYPE> class Base
{
public:void show(TYPE obj)
{
cout << obj << "n" << endl;
}
};
template <class TYPE1,class TYPE2> class Derived:public Base<TYPE2>
{
public: void show2(TYPE1 obj1,TYPE2 obj2)
{
cout << obj1 << " " << obj2 << "n" << endl;
}
};
int main()
{
Derived<char*,double> obj;//基类被实例化为Base<double>
obj.show(3.14);
obj.show2("value of PI is:",3.14159);
}