C++ STL 泛化,全特化,偏特化

  1. 模板特化按对象类型(类和全局函数)分为两种: 类模板的特化和全局模板函数的特化;
  2. 按特化的类型分全特化和偏特化(也就是多个模板参数可以选定只特化一个或者多个),全局模板函数的特化不支持偏特化;
  3. 全局模板函数的特化需要关注几个重要元素函数返回值 函数名 形参类型、个数和顺序,eg:
    template T max_(const T &, const T &)
  4. 类模板的特化需要关注几个重要元素类名,形参类型和个数,形参的顺序倒不重要了;
  5. 模板特化,任何针对模板参数进一步进行条件限制设计的特化版本。《泛型思维》
    全特化就是全部特化,即针对所有的模板参数进行特化。《c++ primer》
    偏特化就是部分特化,即针对部分模板参数进行特化。《c++ primer》
    全特化和偏特化的定义不是很严格,所以有的时候不容易让人理解。
#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()
        {

        }
    };
};

//泛化
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()
{
    templateTest::iterator_traits<int> t1;
    templateTest::iterator_traits<float> t2;
    templateTest::iterator_traits<int *> t3;
    templateTest::iterator_traits<const int *> t4;  
    Test<int, int> t5;
    Test<float, int> t6;
    Test<int, char> t7;
    max(5, 10);
    max(5.5, 10.5);
    system("pause");
}

输出如下:

模版全特化int类型
模版泛化
模版偏特化,特化常规指针
模版偏特化,特化const指针
Test 偏特化
Test 泛化
Test 全特化
模版函数特化
模版函数泛化
请按任意键继续. . .
  • 1
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值