C++类模板的三种特化
1、特化为绝对类型
也就是说直接为某个特定类型做特化,这是我们最常见的一种特化方式,如特化为float,double等
// specialize for floattemplate<>class Compare<float>{public: static bool IsEqual(const float& lh, const float& rh) { return abs(lh - rh) < 10e-3; }};// specialize for doubletemplate<>class Compare<double>{public: static bool IsEqual(const double& lh, const double& rh) { return abs(lh - rh) < 10e-6; }};

2、特化为引用,指针类型
这种特化我最初是在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;
};

3、特化为另外一个模板类
这其实是第二种方式的扩展,其实也是对类型做了某种限定,而不是绝对化为某个具体类型,如下:
// specialize for vector<T>template<class T>class Compare<vector<T> >{public: static bool IsEqual(const vector<T>& lh, const vector<T>& rh) { if(lh.size() != rh.size()) return false; else { for(int i = 0; i < lh.size(); ++i) { if(lh[i] != rh[i]) return false; } } return true;}
};
这就把IsEqual的参数限定为一种vector类型,但具体是vector<int>还是vector<float>,我们可以不关心,因为对于这两种类型,我们的处理方式是一样的,我们可以把这种方式称为“半特化”。
声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
阅读量:164
阅读量:96
阅读量:130
阅读量:71
阅读量:115