模板全特化和偏特化
程序员文章站
2024-01-14 18:32:28
...
模板特化就是告诉编译器我这有更好的实现,走我这边,能更快的执行。
类模板特化分为全特化和偏特化,
全特化就是对所有的模板类型给一个限定,偏特化只限定一部分,可分为个数偏,范围偏
具体如下代码:
//模板类
tempalte<class T1, class T2>
class Person{
public:
void printMem(){
cout<<m_A<<endl;
cout<<m_B<<endl;
}
private:
T1 m_A;
T2 m_B
};
//全特化1
template<class T1, class T2>
class Person<int,int>{
public:
void printMem(){
cout<<m_A<<endl;
cout<<m_B<<endl;
}
private:
int m_A;
int m_B
};
//全特化2
template<>
class Person<int,double>{
public:
void printMem(){
cout<<m_A<<endl;
cout<<m_B<<endl;
}
private:
int m_A;
double m_B
};
//偏特化 个数偏
template<class T2>
class Person<int,T2>{
public:
void printMem(){
cout<<m_A<<endl;
cout<<m_B<<endl;
}
private:
int m_A;
T2 m_B
};
//偏特化 范围偏
template<class T1,class T2>
class Person<T1*,T2>{
public:
void printMem(){
cout<<*m_A<<endl;
cout<<m_B<<endl;
}
private:
T1* m_A;
T2 m_B
};
函数特化:函数只有全特化,不支持偏特化因其重载可以实现偏特化功能
//函数模板
template<class T1,class T2>
void myPrint(T1 a,T2 b) {
cout << a << endl;
cout << b << endl;
}
//全特化
template<>
void myPrint<int,double>(int a,double b) {
cout << a << endl;
cout << b << endl;
}