版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/finewind/article/details/82702912
C++模板
C++模板提供了对逻辑结构相同的数据对象通用行为的定义。这些模板运算对象的类型不是实际的数据类型,而是一种参数化的类型。C++模板分为类模板和函数模板那。
类模板示例:
template <class T>
class TClass
{
public:
//...
private:
T member;
};
函数模板示例:
template <class T>
T max(const T a, const T b)
{
return a > b ? a : b;
}
模板特化
有时,针对特定的类型,需要对模板进行特化,也就是所谓的特殊处理。比如如下代码:
template <class T>
class TClass
{
public:
bool equal(const T &a, const T &b);
};
template <class T>
bool TClass<T>::equal(const T &a, const T &b)
{
return (a == b);
}
上述类中只实现了一个equal()方法,用于比较两个参数是否相等。但若用于比较double类型的参数,判断相等需要进行特殊化处理,即要特化模板,代码如下:
#include <math.h>
#include <iostream>
using std::endl;
usging std::cout;
// 已经不具有template的意思了,已经明确为double了
template <>
class TClass<double>
{
public:
bool equal(const double &a, const double &b);
};
bool TClass<double>::equal(const double &a, const double &b)
{
return (fabs(a-b) < 10e-3);
}
// 测试代码
int main()
{
TClass<int> obj_int;
TClass<double> obj_double;
cout << obj_int(2, 2) << endl;
cout << obj_double(2.00003, 2.00001) << endl;
return 0;
}
模板偏特化
模板偏特化,指提供另一份template定义式,而其本身仍为templatized。也就是说,针对template参数更进一步的条件限制所设计出来的一个特化版本。这种偏特化在STL中随处可见。比如:
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;
};
示例代码:
template <class T>
class TestClass
{
public:
TestClass() { cout << "T" << endl; }
};
template <class T>
class TestClass<T*>
{
public:
TestClass() { cout << "T*" << endl; }
};
template <class T>
class TestClass<const T*>
{
public:
TestClass() { cout << "const T*" << endl; }
};
int main()
{
// 偏特化测试
TestClass<int> obj_common;
TestClass<int*> obj_spec1;
TestClass<const int *> obj_spec2;
}
模板特化与偏特化的区别在于,模板特化以后,实际上其本身已经不是templatized,而偏特化,仍然带有templatized。
特化与偏特化的调用顺序
对于模板、模板的特化和模板的偏特化都存在的情况下,编译器在编译阶段进行匹配时,是如何抉择的呢?从哲学的角度来说,应该先照顾最特殊的,然后才是次特殊的,最后才是最普通的。编译器进行抉择也是尊从这个道理。