c++ - 为什么列表迭代器在 SGI STL 实现中具有三个模板参数?

标签 c++ templates stl iterator

我在阅读 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 中引入了 referencepointer 成员别名他的类(class) Efficient Programming with Components

简而言之,Stepanov 最初认为 – 给定一个迭代器 it*it 可以安全地假定为 value_type& 类型,并且&*itvalue_type* 类型。然而,微软表示将投票反对将 STL 纳入标准,除非它可以容纳多种内存模型,当时这些模型包括具有微小、巨大和长指针的模型。因此,引入了referencepointer。引用他的演讲:

"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/

相关文章:

c++ - 使用 Visual C++ 开发人员工具运行的代码块

c++ - 模板 模板参数

c++ - 如何调试 STL/C++ 的 GCC/LD 链接过程

c++ - 依赖于构造函数的类模板参数

c++ - priority_queue<> 比较指针?

c++ - 使用指向 STL vector 的指针是个好主意吗?

c++ - 如果括号里是case,需要换行吗?

c++ - VSCode 终端 ctrl-click in out of source build 找不到文件

c++ - 如何监控包含所有子文件夹和文件的文件夹?

templates - 如何在Grails 3.x中创建可重用的布局和脚手架模板