65,180
社区成员




// 节录自SGI STL <stl_iterator.h>
// 五种迭代器类型
struct input_iterator_tag {};
struct output_iterator_tag {};
struct forward_iterator_tag : public input_iterator_tag {};
struct bidirectional_iterator_tag : public forward_iterator_tag {};
struct random_access_iterator_tag : public bidirectional_iterator_tag {};
// 为避免写码时挂㆒漏万,自行开发的迭代器最好继承自㆘面这个std::iterator
template <class Category, class T, class Distance = ptrdiff_t,
class Pointer = T*, class Reference = T&>
struct iterator {
typedef Category iterator_category;
typedef T value_type;
typedef Distance difference_type;
typedef Pointer pointer;
typedef Reference reference;
};
// 「榨汁机」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;
};
// 针对原生指标(native pointer)而设计的traits 偏特化版。
template <class T>
struct iterator_traits<T*> {
typedef random_access_iterator_tag iterator_category;
typedef T value_type;
typedef ptrdiff_t difference_type;
typedef T* pointer;
typedef T& reference;
};
//下面是我加来测试的,发现编译器提示,error-type;
//我打开VS中的源码发现不是这么用的。
//VS中是typedef一个类型 然后用新声明的类型typedef typename;
int main()
{
iterator_traits<int>::difference_type d;
}
#include<iostream>
using namespace std;
template<typename T>
class CT
{
public:
typedef T type;
};
template<typename F>
class CF
{
public:
//下面两个我觉得应该是等效,主要区别是在使用时的区别
//如果使用时定义如下,CF<int>::value x=0;
//typedef typename F::type type_value;这句就会报错。
//但是typedef typename CT<F>::type value;就不会报错
typedef typename F::type type_value;
typedef typename CT<F>::type value;
};
int main()
{
////这里出错了,因为需要传递进来的是模板类不能是内置类型。
//CF<int>::type_vale x;
CF<CT<int>>::type_value i=0; //正确传进来的是模板。
int j=0;
if(typeid(i) == typeid(j))
cout<<"yes";
}
#include<iostream>
using namespace std;
struct input_iterator_tag {};
struct output_iterator_tag {};
struct forward_iterator_tag : public input_iterator_tag {};
struct bidirectional_iterator_tag : public forward_iterator_tag {};
struct random_access_iterator_tag : public bidirectional_iterator_tag {};
// 为避免写码时挂㆒漏万,自行开发的迭代器最好继承自㆘面这个std::iterator
template <class Category/*, class T, class Distance = ptrdiff_t,
class Pointer = T*, class Reference = T&*/>
struct iterator {
typedef Category iterator_category;
/*typedef T value_type;
typedef Distance difference_type;
typedef Pointer pointer;
typedef Reference reference;
*/
};
// 「榨汁机」traits
template <class Iterator>
struct iterator_traits {
typedef typename iterator<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;
*/
};
int main()
{
iterator_traits<int>::iterator_category d;
}