Learning summary of STL iterators in programming methodology Traits

Value_type iterator corresponding type, for example: vector <int> :: iterator it; type iterator it is actually int *, and the corresponding iterator type herein refers to a corresponding type int ,, i.e. herein refers to an iterative iterator type of object.
When using an iterator may sometimes be necessary to use a corresponding type value_type iterator, for example, when a function use iterator type value_type return value is needed, but this time we only know the type of iterator, how to obtain the iterator value_type?
STL method of solving this problem:
When STL iterators are defined, while the statement embedded type value_type, namely:
. 1 Template < class T>
 2  struct Iterator {
 . 3      typedef the value_type T; // declare inline type the value_type 
. 4      T * PTR;
 . 5 };

Thus when using the above-described requirements may be similar to the following:

. 1 Template < class the I> 
 2 typename :: the value_type the I // return type 
. 3  func_exp (the I ITER) {
 . 4      return * ITER;
 . 5 }

typename responsible to tell the compiler I :: value_type as a type, because I was the type of template before the template is instantiated, the compiler does not know what I is, I do not know I :: value_type indicates the type.

 

But the native pointer as an iterator, we can not declare its embedded type value_type, because we do not define the iterator.

I.e., there are two cases, as the primary pointer and custom iterator iterator class type, a method of obtaining the same can not be obtained when it value_type.

 

Then use the traits programming skills, it can be get value_type independent, using partial template specialization to solve the above-mentioned two different situations:

. 1 Template < class the I>
 2  struct iterator_traits {
 . 3      typedef typename the value_type the value_type the I ::;
 . 4  };
 . 5  
. 6 Template < class T>
 . 7  struct iterator_traits <T *> { // specializations when native pointer as an iterator 
8      T the value_type typedef;
 . 9 };

At this time value_type reuse, as follows, native pointer acquired solve problems value_type:

. 1 Template < class T> 
 2 iterator_traits <T> :: value_type // return type, estimated using iterator_traits value_type type 
. 3  FUNC (T ITER) {
 . 4      return * ITER;
 . 5 }

traits "characteristic extraction machine":

 

 

Guess you like

Origin www.cnblogs.com/dabai56/p/11432854.html