有人可以解释为什么如果我取消注释以下行将无法编译以下内容foo::const_iterator j = f.begin();
,但是如果我使用foo::const_iterator j = f.cbegin();
行,它将进行编译?我正在尝试使该行能够与std::vector
示例一起使用。
#include <vector>
struct foo {
struct node { };
node *first = nullptr, *last = nullptr;
struct base_iterator {
node* ptr;
base_iterator (node* n) : ptr(n) { }
};
struct iterator : base_iterator { using base_iterator::base_iterator; };
struct const_iterator : base_iterator { using base_iterator::base_iterator; };
iterator begin() { return iterator(first); }
const_iterator begin() const { return const_iterator(first); }
const_iterator cbegin() const { return const_iterator(first); }
};
// Test
int main() {
foo f;
foo::iterator i = f.begin();
// foo::const_iterator j = f.begin(); // Won't compile because f is not const.
// foo::const_iterator j = f.cbegin(); // Will compile fine.
std::vector<int> v;
std::vector<int>::const_iterator it = v.begin(); // Compiles even though v is not const.
}
最佳答案
它适用于std::vector
,因为所有标准库容器的迭代器均设计为支持iterator
-> const_iterator
转换。它旨在模仿指针转换的工作方式。
只要您的两个迭代器是用户定义的类,就需要显式添加它。您有两种选择:
转换构造函数:
struct iterator : base_iterator { using base_iterator::base_iterator; };
struct const_iterator : base_iterator {
using base_iterator::base_iterator;
const_iterator(const iterator& other) : base_iterator(other) {}
};
转换运算符:
struct const_iterator : base_iterator { using base_iterator::base_iterator; };
struct iterator : base_iterator {
using base_iterator::base_iterator;
operator const_iterator() const { /* ... */ }
};
关于c++ - 从begin()而不是cbegin()获取const_iterator,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47794223/