我在阅读 SGI STL 的列表迭代器实现时遇到问题。
template<class T>
struct __list_node {
void *prev;
void *next;
T data;
};
template<class T, class Ref, class Ptr>
struct __list_iterator {
typedef __list_iterator<T, T&, T*> iterator;
typedef __list_iterator<T, Ref, Ptr> self;
...
typedef T value_type;
typedef Ptr pointer;
typedef Ref reference;
typedef __list_node<T>* link_type;
...
link_type node;
...
reference operator*() const { return (*node).data; }
pointer operator-> const { return &(operator*()); }
self& operator++() { ... }
self operator++(int) { ... }
...
...
};
那么,为什么会有三个模板参数呢?
如果只有 class T
存在怎么办?喜欢下面的东西。
template<class T>
struct __list_iterator {
typedef __list_iterator<T> iterator;
typedef __list_iterator<T> self;
...
typedef T value_type;
typedef T* pointer;
typedef T& reference;
...
...
};
我想知道对于某些特定的 class T
来说三个参数是否是必须的,或者某些我无法弄清楚的原因。
希望有人能帮助我。非常感谢!
最佳答案
Alexander Stepanov(STL 的发明者)解释了为什么在 Lecture 11 期间在 STL 中引入了 reference
和 pointer
成员别名他的类(class) Efficient Programming with Components。
简而言之,Stepanov 最初认为 – 给定一个迭代器 it
,*it
可以安全地假定为 value_type&
类型,并且&*it
为 value_type*
类型。然而,微软表示将投票反对将 STL 纳入标准,除非它可以容纳多种内存模型,当时这些模型包括具有微小、巨大和长指针的模型。因此,引入了reference
和pointer
。引用他的演讲:
"This is not particularly harmful, but it obfuscates things. It is of course loved by language specialists; it provides them steady employment."
有趣的是,即使 Stepanov 改变了 STL 的整个架构以满足其要求,Microsoft 仍然决定投票反对包含在内。
类的相关部分是here .
关于c++ - 为什么列表迭代器在 SGI STL 实现中具有三个模板参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51100746/