C++类模板的三种特化

发表于:2016-2-14 09:43

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:玄冬    来源:51Testing软件测试网采编

  说起C++的模板及模板特化, 相信很多人都很熟悉 ,但是说到模板特化的几种类型,相信了解的人就不是很多。我这里归纳了针对一个模板参数的类模板特化的几种类型, 一是特化为绝对类型; 二是特化为引用,指针类型;三是特化为另外一个类模板。
  这里用一个简单的例子来说明这三种情况:
  // general version
  template<class T>
  class Compare
  {
  public:
  static bool IsEqual(const T& lh, const T& rh)
  {
  return lh == rh;
  }
  };
  这是一个用于比较的类模板,里面可以有多种用于比较的函数, 以IsEqual为例。
  一、特化为绝对类型
  也就是说直接为某个特定类型做特化,这是我们最常见的一种特化方式, 如特化为float, double等
// specialize for float
template<>
class Compare<float>
{
public:
static bool IsEqual(const float& lh, const float& rh)
{
return abs(lh - rh) < 10e-3;
}
};
// specialize for double
template<>
class Compare<double>
{
public:
static bool IsEqual(const double& lh, const double& rh)
{
return abs(lh - rh) < 10e-6;
}
};
  二、特化为引用,指针类型
  这种特化我最初是在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;
};
// specialize for _Tp*
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;
};
// specialize for const _Tp*
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;
};
21/212>
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号