http://blog.csdn.net/chenhanzhun/article/details/39230529
前言
在STL编程中,容器和算法是独立设计的,即数据结构和算法是独立设计的,连接容器和算法的桥梁就是迭代器了,迭代器使其独立设计成为可能。Traits编程技术是STL中最重要的编程技术,Traits可以获取一个类型的相关信息。在学习《STL源码剖析》时,看到关于这方面的知识,在这期间查找了一些资料,下面是我对该技术的理解。
Traits编程技术
Traits可以获取一个类型的相关信息,首先我们看下面的程序:
- template <class T, class type>
- void function(T t, type u) {
- type temp;
- // ... The rest work of function…
- }
- template <class T, class type>
- void function(T iter, type u)
- {
- type temp; // 通过模板参数推导获得temp变量的类型
- ....
- }
- template <class T>
- void func(T iter)
- {
- function(iter, *iter);
- }
- int main()
- {
- int i = 12;
- func(&i)
- }
若我们要知道用户自定义类型的函数返回值类型,我们可以使用内嵌型别技术就可以知道返回值的类型;看下面程序:
- templates <class T>
- struct Iterator
- {
- typedef T value_type;//内嵌型别声明
- ...
- };
- template <class Iterator>
- typename Iterator::value_type //返回值类型
- GetValue(Iterator iter)
- {
- return *iter;
- }
- int main()
- {
- ...
- Iterator<int> ite(new int(9));
- std::cout<<GetValue(ite)<<std::endl;
- return 0;
- }
- template <class Iterator>
- struct iterator_traits {
- typedef typename Iterator::value_type value_type;
- ...
- };
- template <class Iterator>
- typename iterator_traits<Iterator>::value_type //返回值类型
- GetValue(Iterator iter)
- {
- return *iter;
- }
- template <class Tp>
- struct iterator_traits<Tp*> {
- typedef Tp value_type;
- ...
- };
- template <class Tp>
- struct iterator_traits<const Tp*> {
- typedef Tp value_type;
- ...
- };
我们之所以要萃取 (Traits) 迭代器相关的类型,就是要把迭代器相关的类型用于声明局部变量、用作函数的返回值等一系列行为。对于原生指针和 point-to-const 类型的指针,采用模板偏特化技术对其进行特殊处理。要使用Traits功能,则必须自行以内嵌型别定义的方式定义出相应型别。我们上面讲解的只是迭代器其中一种类型value type,在迭代器中还有其他类型:
- 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; //迭代器引用之物
- };