c++模板特化

针对一个模板参数的类模板特化的几种类型, 一是特化为绝对类型; 二是特化为引用,指针类型;三是特化为另外一个类模板

这里用一个简单的例子来说明这三种情况:

template<class T>

class compare

{

public:

  static bool IsEqual(const T& lh, const T& rh)

  {

    return lh == rh;

  }

}

一、特化为绝对类型

也就是直接为某个特定的类型做特化。

template<>

class compare<float>

{...}

template<>

class compare<double>

{...}

二、特化为引用,指针类型

这种特化是在stl源码的iterator_traits特化中发现的,如下:

template <class _Iterator>
struct iterator_traits {
  typedef typename _Iterator::iterator_category iterator_category;
  typedef typename _Iterator::value_type        value_type;
  typedef typename _Iterator::difference_type   difference_type;
  typedef typename _Iterator::pointer           pointer;
  typedef typename _Iterator::reference         reference;
};

template<class _Tp>

struct iterator_traits<_Tp*> {
  typedef random_access_iterator_tag iterator_category;
  typedef _Tp                         value_type;
  typedef ptrdiff_t                   difference_type;
  typedef _Tp*                        pointer;
  typedef _Tp&                        reference;
};

template <class _Tp>
struct iterator_traits<const _Tp*> {
  typedef random_access_iterator_tag iterator_category;
  typedef _Tp                         value_type;
  typedef ptrdiff_t                   difference_type;
  typedef const _Tp*                  pointer;
  typedef const _Tp&                  reference;
};

当然,除了T*,我们也可以将T特化为const T*,T&,const T&。

template<class T>

class compare<T*>

{...}

这种特化其实是就不是一种绝对的特化, 它只是对类型做了某些限定,但仍然保留了其一定的模板性,这种特化给我们提供了极大的方便, 如这里, 我们就不需要对int*, float*, double*等等类型分别做特化了。

三、特化为另外一个类模板

其实这也是第二种方式的扩展,其实也是对类型做了某种限定,而不是绝对化为某个具体类型,如下:

template<class T>

class compare<vector<T> >

{...}

原文地址:https://www.cnblogs.com/lverson/p/4346439.html