'iterator' 可以只键入'const_iterator' 的子类吗?

2022-01-24 00:00:00 containers iterator casting c++

在关于迭代器的另一个问题之后我对自定义容器有一些疑问.在我的容器中,iteratorconst_iterator 的子类,因此我可以免费"从非 const 转换为 const.但这是否允许,或者这样的设置是否有任何缺点或不工作的情况?

After another question about iterators I'm having some doubts about custom containers. In my container, iterator is a subclass of const_iterator, so that I get conversion from non-const to const "for free". But is this allowed or are there any drawbacks or non-working scenarios for such a setup?

推荐答案

是的,这很好.例如,这就是 VC10 的 vector 迭代器实现的结构.请参阅 中的 _Vector_iterator_Vector_const_iterator.

Yes, this is fine. This is how VC10's implementation of the iterators for vector are structured, for example. See _Vector_iterator and _Vector_const_iterator in <vector>.

顺便说一句,编写迭代器很困难.值得您花时间学习和使用 boost::iterator 库.

By the way, writing iterators is hard. It's worth your time to learn and use the boost::iterator library.

相关文章