C++ 模板类解析

具体模板类作用这边就不细说了,下面主要是描述下模板类的使用方法以及注意的一些东西。

#include <iostream>
using namespace std;
template <typename numtype>
//定义类模板
class Compare
{
   public :
   Compare(numtype a,numtype b) 
   {x=a;y=b;}
   numtype max( )
   {return (x>y)?x:y;}
   numtype min( )
   {return (x<y)?x:y;}
   private :
   numtype x,y;
};
int main( )
{
   Compare<int > cmp1(3,7);//定义对象cmp1,用于两个整数的比较
   cout<<cmp1.max( )<<″ is the Maximum of two integer numbers.″<<endl;
   cout<<cmp1.min( )<<″ is the Minimum of two integer numbers.″<<endl<<endl;
   Compare<float > cmp2(45.78,93.6); //定义对象cmp2,用于两个浮点数的比较
   cout<<cmp2.max( )<<″ is the Maximum of two float numbers.″<<endl;
   cout<<cmp2.min( )<<″ is the Minimum of two float numbers.″<<endl<<endl;
   Compare<char> cmp3(′a′,′A′); //定义对象cmp3,用于两个字符的比较
   cout<<cmp3.max( )<<″ is the Maximum of two characters.″<<endl;
   cout<<cmp3.min( )<<″ is the Minimum of two characters.″<<endl;
   return 0;
}

使用方法

1)先写出一个实际的类。由于其语义明确,含义清楚,一般不会出错。

2)将此类中准备改变的类型名(如int要改变为float或char)改用一个自己指定的虚拟类型名(如上例中的numtype)。

3)在类声明前面加入一行,格式为
          template <typename 虚拟类型参数>,如
          template <typename numtype> //注意本行末尾无分号
          class Compare
          {…}; //类体

4)用类模板定义对象时用以下形式:
          类模板名<实际类型名> 对象名;
          类模板名<实际类型名> 对象名(实参表列);
          如
          Compare<int> cmp;
          Compare<int> cmp(3,7);

    说明:Compare是类模板名,而不是一个具体的类,类模板体中的类型numtype并不是一个实际的类型,只是一个虚拟的类型,无法用它去定义对象。
必须用实际类型名去取代虚拟的类型,具体的做法是:
       Compare <int> cmp(4,7);
      即在类模板名之后在尖括号内指定实际的类型名,在进行编译时,编译系统就用int取代类模板中的类型参数numtype,这样就把类模板具体化了,或者说实例化了。

5) 如果在类模板外定义成员函数,应写成类模板形式:
         template <class 虚拟类型参数>
         函数类型 类模板名<虚拟类型参数>::成员函数名(函数形参表列) {…}

    eg:

      template <nametype numtype>
           numtype Compare<numtype>::max( )
           {{return (x>y)?x:y;}

补充说明

1)类模板的类型参数可以有一个或多个,每个类型前面都必须加class,如
          template <class T1,class T2>
          class someclass
          {…};
          在定义对象时分别代入实际的类型名,如
          someclass<int,double> obj;

2)和使用类一样,使用类模板时要注意其作用域,只能在其有效作用域内用它定义对象。

参考:http://see.xidian.edu.cn/cpp/biancheng/view/213.html

原文地址:https://www.cnblogs.com/menghuizuotian/p/3773130.html