Partial Specialization模板偏特化

    在上一篇博客中,我们介绍了模板的全特化。这里,我们将继续介绍模板的偏特化。偏特化包括两种,个树的偏和范围的偏。

    个数的偏

    如果模板参数有两个,你想绑定其中一个,这就实现了模板的偏特化。但需要注意的是,要按顺序从左到右绑定模板参数,不能跳跃式绑定第一三五个模板参数。

template<typename T, typename Alloc=...>
class vector
{
...
};

template<typename Alloc=...>
class vector<bool, Alloc> //绑定了T
{
...
};

    范围的偏

    如果我们设计接收任意类型的T,要是我们缩小接收范围为指向任意类型T的指针,这就是模板的偏特化。

template<typename T>
class C
{
...
};

template<typename T>
class C<T*>
{
...
};
#include<iostream>

using std::cout;
using std::endl;

template<typename T1, typename T2>
class Test
{
public:
  Test(T1 i, T2 j)
  : a(i), b(j)
  {
    cout << "模板类" << endl;
  }
private:
  T1 a;
  T2 b;
};

template<> //全特化,模板参数都被指定,故此处<>为空 
class Test<int, char>
{
public:
  Test(int i, char j)
  : a(i), b(j)
  {
    cout << "全特化" << endl;
  }
private:
  int a;
  char b;
};

template<typename T2> //由于指定了一部分参数,剩下未指定的参数需在参数列表中 
class Test<char, T2>
{
public:
  Test(char i, T2 j)
  : a(i), b(j)
  {
    cout << "个数偏特化" << endl;
  }
private:
  char a;
  T2 b;
}; 

template<typename T1, typename T2>
class Test<T1*, T2*> 
{
public:
  Test(T1* i, T2* j)
  : a(i), b(j)
  {
    cout << "指针偏特化" << endl;
  }
private:
  T1* a;
  T2* b;
};

template<typename T1, typename T2> //同理这也是范围上的偏特化
class Test<T1 const, T2 const>
{
public:
  Test(T1 i,T2 j)
  :a(i),b(j)
  {
    cout<<"const偏特化"<<endl;
  }
private:
  T1 a;
  T2 b;
};

int main()
{
  int a;
  Test<double, double> t1(0.1,0.2);
  Test<int, char> t2(1, 'A');
  Test<char, bool> t3('B', true);
  Test<int*, int*> t4(&a, &a);
  Test<int const, int const> t5(3,6);
  return 0; 
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值