iterator_traits — Struktura
Struct pomocnika szablon pozwala określić wszystkie definicje typów krytycznych, mających iterację.
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 difference_type distance_type;
typedef typename Iterator::pointer pointer;
typedef typename Iterator::reference reference;
};
template<class Type>
struct iterator_traits<Type*> {
typedef random_access_iterator_tag iterator_category;
typedef Type value_type;
typedef ptrdiff_t difference_type;
typedef difference_type distance_type;
typedef Type *pointer;
typedef Type& reference;
};
template<class Type>
struct iterator_traits<const Type*> {
typedef random_access_iterator_tag iterator_category;
typedef Type value_type;
typedef ptrdiff_t difference_type;
typedef difference_type distance_type;
typedef const Type *pointer;
typedef const Type& reference;
};
Uwagi
Struktura szablonu określa typy elementów członkowskich
iterator_category: synonim Iterator::iterator_category.
value_type: synonim Iterator::value_type.
difference_type: synonim Iterator::difference_type.
distance_type: synonim Iterator::difference_type.
wskaźnik: synonim Iterator::pointer.
Odwołanie: synonim Iterator::reference.
Częściowe specjalizacje określenia typów krytycznych związanych z wskaźnikiem obiektu typu typu * lub const typu *.
W tej implementacji, można również użyć kilku funkcji szablonu, które nie wykorzystanie częściowa specjalizacja:
template<class Category, class Type, class Diff>
C _Iter_cat(const iterator<Category, Ty, Diff>&);
template<class Ty>
random_access_iterator_tag _Iter_cat(const Ty *);
template<class Category, class Ty, class Diff>
Ty *_Val_type(const iterator<Category, Ty, Diff>&);
template<class Ty>
Ty *_Val_type(const Ty *);
template<class Category, class Ty, class Diff>
Diff *_Dist_type(const iterator<Category, Ty, Diff>&);
template<class Ty>
ptrdiff_t *_Dist_type(const Ty *);
te określają wiele takich samych typów bardziej pośrednio.Funkcje te są używane jako argumenty na wywołanie funkcji.Jedynym ich celem jest dostarczanie parametr klasy przydatnego szablonu do wywołanej funkcji.
Przykład
// iterator_traits.cpp
// compile with: /EHsc
#include <iostream>
#include <iterator>
#include <vector>
#include <list>
using namespace std;
template< class it >
void
function( it i1, it i2 )
{
iterator_traits<it>::iterator_category cat;
cout << typeid( cat ).name( ) << endl;
while ( i1 != i2 )
{
iterator_traits<it>::value_type x;
x = *i1;
cout << x << " ";
i1++;
};
cout << endl;
};
int main( )
{
vector<char> vc( 10,'a' );
list<int> li( 10 );
function( vc.begin( ), vc.end( ) );
function( li.begin( ), li.end( ) );
}
Wymagania
Nagłówek: <iterator>
Przestrzeń nazw: std