C++模版中的类属参数可以是任何类型,与JAVA中的泛型不同,是一种无约束类属类,即实际参数的各个类型不要求有共同的祖先类。而JAVA中的泛型定义,可以指定类属参数必须实现了某个接口。
因此,C++中定义了一个模版,实际的类属参数可以是任何类型,模版类属中的代码也可以复用。但是如果我们想针对不同的类属参数,做特殊化的处理,该如何定义呢。下面
就是对模版的类属参数作特殊处理的例子:
/*一般化设计*/
template<class I,class O>
struct testClass
{
testClass(){ cout<<"I,O"<<endl; }
};
/*特殊化设计*/
template<class T>
struct testClass<T*,T*>
{
testClass(){ cout<<"T*,T*"<<endl;}
};
template<class T>
struct testClass<const T*,T*>
{
testClass(){ cout<<"const T*,T*"<<endl;}
};
int main()
{
testClass<int,char> obj1;
testClass<int*,int*> obj2;
testClass<const int*,int*> obj3;
return 0;
}
如果我们未做特殊化的定义,程序也可以正常运行。可以删除某个特殊化定义,观察程序的运行结果,来理解模版参数的特殊处理。