模板类专用化以处理其自己的类型

Template class specialization to handle its own type

本文关键字:处理 自己的 类型 专用      更新时间:2023-10-16

我一直在玩模板来感受它们,我想在它自己的类型上做一个类专业化。我在互联网上搜索了一段时间,但我没有发现提到这一点。

例如,如果我有一个class Array

template<class T>
class Array{
 ...
 void print();
}

T=Array<unspecified type>时是否可以专门化方法print()

template<class T>
void Array<Array<T>>::print(){
    //do something diffrent for array of array
    //this code wont work
}

我设法做到了

template<>
void Array<Array<int>>::print(){
    //print in matrix format
    //this code works
}

我不认为这个功能非常有用,但我仍然很好

AFAIK 您只能对整个班级执行专业化。一旦我需要这样的东西(实际上,我只需要两个typedef是不同的),所以我创建了一个辅助类,它只包含必须专用的成员,并使主体类继承它。

有一个称为部分专用化的功能,您可以在其中应用类似的东西。但是,我不认为您可以部分专用于成员函数而不部分专用于整个类。