C++模板全特化和偏特化

模板特化,任何针对模板参数进一步进行条件限制设计的特化版本。《泛型思维》

全特化就是全部特化,即针对所有的模板参数进行特化。《c++ primer》
偏特化就是部分特化,即针对部分模板参数进行特化。《c++ primer》

全特化偏特化的定义不是很严格,所以有的时候不容易让人理解。

全特化

#include <iostream>
using namespace std;

template<class T1, class T2>
class A
{
public:
    A():i(65),j(66) {
        cout<<"原始:"<<i<<" "<<j<<endl;
    }
    T1 i;
    T1 j;
};

template<>
class A<int, int>
{
public:
    A():i(65),j(66) {
        cout<<"全特化:"<<i<<" "<<j<<endl;
    }
    int i;
    int j;
};
int main(int argc, char *argv[])
{
	A<char, char> a;
	A<int, int> b;
	return 0;
}

输出:

原始:A B
全特化:65 66

偏特化

#include <iostream>
using namespace std;

template<class T1, class T2>
class A
{
public:
    A():i(65),j(66) {
        cout<<"原始:"<<i<<" "<<j<<endl;
    }
    T1 i;
    T1 j;
};

template<class T2>
class A<char, T2>  //注意:char 一定要加
{
public:
    A():i(65),j(66) {
        cout<<"全特化:"<<i<<" "<<j<<endl;
    }
    char i;//局部特化
    T2 j;
};
int main(int argc, char *argv[])
{
	A<char, char> a;
	A<char, int> b;
	return 0;
}

输出:

全特化:A B
全特化:A 66

猜你喜欢

转载自blog.csdn.net/QQ2558030393/article/details/94553501