C++类模板 template

时间:2023-03-09 07:09:24
C++类模板 template <class T>

C++在发展的后期增加了模板(template )的功能,提供了解决这类问题的途径。可以声明一个通用的类模板,它可以有一个或多个虚拟的类型参数。

比如:

  1. class Compare_int
  2. class Compare_float

都是比较大小的函数,只是参数类型不同,于是用一个类模版综合成一个函数:

template <class numtype> //声明一个模板,虚拟类型名为numtype
class Compare //类模板名为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;
};

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

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

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

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