【C++ Primer | 16】容器适配器全特化、偏特化

上面对模板的特化进行了总结。那模板的偏特化呢?所谓的偏特化是指提供另一份模板定义式,而其本身仍为模板;也就是说,针对模板参数更进一步的条件限制所设计出来的一个特化版本。这种偏特化的应用在STL中是随处可见的。比如

1.测试代码: 

#include <iostream>
using namespace std;

namespace templateTest {

    //模版泛化
    template<typename T>
    class iterator_traits
    {
    public:
        iterator_traits() { cout << "模版泛化" << endl; }
        ~iterator_traits() {}
    };

    //偏特化
    template<typename T>
    class iterator_traits<T*>
    {
    public:
        iterator_traits() { cout << "模版偏特化,特化常规指针" << endl; }
        ~iterator_traits() {};
    };

    //偏特化
    template<typename T>
    class iterator_traits<const T*>
    {
    public:
        iterator_traits() { cout << "模版偏特化,特化const指针" << endl; }
        ~iterator_traits() {}
    };

    //全特化
    template<>
    class iterator_traits<int>
    {
    public:
        iterator_traits() { cout << "模版全特化int类型" << endl; }
        ~iterator_traits() {}
    };
};

int main()
{
    templateTest::iterator_traits<int> t1;         //  模版全特化int类型
    templateTest::iterator_traits<float> t2;       //  模版泛化
    templateTest::iterator_traits<int*> t3;        //  模版偏特化,特化常规指针
    templateTest::iterator_traits<const int*> t4;  //  模版偏特化,特化const指针
}

2. 测试代码:

#include <iostream>
using namespace std;

//泛化
template<class U, class T>
class Test
{
public:
    Test() { cout << "Test 泛化" << endl; }
};

//偏特化
template<class T>
class Test<int, T>
{
public:
    Test() { cout << "Test 偏特化" << endl; }
};

//全特化
template<>
class Test<int, char>
{
public:
    Test() { cout << "Test 全特化" << endl; }
};

/*--------------------------------------------------*/

template<typename T>
void max(const T& t1, const T& t2)
{
    cout << "模版函数泛化" << endl;

}

//其实函数模版不存在偏特化,只有全特化
template<>
void max<int>(const int& t1, const int& t2)
{
    cout << "模版函数全特化" << endl;
}

void main()
{
    Test<int, int> t1;   // Test 偏特化
    Test<float, int> t2; // Test 泛化
    Test<int, char> t3;  // Test 全特化
    max(5, 10);         //  模版函数特化
    max(5.5, 10.5);     //  模版函数泛化
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值