【发布时间】:2018-05-31 12:42:58
【问题描述】:
以下是 Scott Meyers Effective STL 关于迭代器第 26 条的文本。
typedef deque<int> IntDeque; //STL container and
typedef lntDeque::iterator Iter; // iterator types are easier
typedef lntDeque::const_iterator Constlter; // to work with if you
// use some typedefs
Iter i;
Constlter ci;
… //make i and ci point into
// the same container
if (i == ci ) ... //compare an iterator
// and a const_iterator
我们在这里所做的只是将两个迭代器与一个容器进行比较,这种比较是 STL 的基础。唯一的转折是一个对象是迭代器类型,一个是 const_iterator 类型。这应该没有问题。迭代器应该被隐式调用到 const_iterator 中。并且应该在两个 const_iterators 之间进行比较。
对于设计良好的 STL 实现,这正是发生的情况,但对于其他实现,代码将无法编译。原因是这样的实现将 const_iterators 的 operator== 声明为成员函数而不是非成员函数,但问题的原因可能比解决方法对您更不感兴趣,即交换顺序迭代器,像这样:
if (ci == i)... // workaround for when the
// comparison above won't compile
上面的问题
- 为什么作者的意思是只调用了 const_iterator 成员函数,也有可能为 operator == 调用了迭代器成员函数?
【问题讨论】:
-
这本书已有 15 年以上的历史,讨论了早期的 C++98 实现。在原始标准中,从 iterator 到 const_iterator 的隐式转换可能没有明确说明,因此实现有所不同。