当容器定义为 const 时,带有自定义迭代器的自定义容器不起作用
或多或少一切都在主题中。
当我有
func(my_cont& c)
{ c.begin() };
东西工作,但
func(const my_cont& c)
{ c.begin() };
不起作用时,编译器声称无法将其从 my_cont<..> 转换为 const my_cont<..>....
容器和我的自定义迭代器处理此问题有哪些要求?
More or less everything is in the topic.
when I have
func(my_cont& c)
{ c.begin() };
things works, but
func(const my_cont& c)
{ c.begin() };
doesn't work, compiler claims that cant convert this to const my_cont<..>.... from my_cont<..>
What are the requirements for the container and my custom iterator to handle this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您的容器类应该有两个 begin() 和 end() 实现 - 一个返回迭代器,另一个返回 const_iterator:
const_iterator 不能用于修改它指向的对象。
Your container class should have two implementations of begin() and end() - one returning iterator and another returning const_iterator:
const_iterator cannot be used to modify the object that it points to.
您需要添加一个 const
begin()
,如下所示:您还必须定义一个
const_iterator
类型。You need to add a const
begin()
, something like this:You'll have to define a
const_iterator
type also.这是一篇关于编写迭代器的好文章:
http://www.aristeia.com/Papers/CUJ_June_2001.pdf
大多数人都有注意到您需要一个返回 const_iterator 的 begin() 和 end() 的 const 版本。
大多数人忘记的是迭代器应该能够隐式转换为 const_iterator。否则,很难从非成本对象中获得 const 迭代器(没有大量令人讨厌的强制转换)。
注意:上面的调用实际上会调用非成本版本的 begin() 和 end()。但它们被分配给 const_iterator。因此,您的迭代器必须可转换为 const_iterator 才能使上述代码正常工作(注意:没有从 const_iterator 到迭代器的隐式转换。这应该采用显式 const_cast,因为它本质上是危险的)。
Here is a good article on writing iterators:
http://www.aristeia.com/Papers/CUJ_June_2001.pdf
As most people have noted you need a const version of begin() and end() that returns a const_iterator.
What most people have forgotten is that an iterator should be able to implicitly convert into a const_iterator. Otherwise it is hard to get a const iterator from a non cost object (without a lot of nasty casts).
Note above: The above calls will actually call the non cost versions begin() and end(). But they are being assigned to a const_iterator. So your iterators must be convertible to const_iterator for the above code to work (Note: There is no implicit conversion from const_iterator to iterator. That should take an explicit const_cast as it is inherently dangerous).
这正是STL为容器实现cost_iterator的原因。只是检查它在STL中是如何实现的,我不确定你能找到更好的解决方案。
This is exactly the reason why STL implements cost_iterator for containers. Just check how is it implemented in STL, I'm not sure you can find any better solution.
您只能在 const 对象上调用 const 成员函数(或在 易失性对象上调用易失性成员函数)。
编译器告诉我们缺少
iterator my_cont::begin() const
。You can only call const member functions on a const object (or volatile member functions on a volatile object).
The compiler is telling that
iterator my_cont::begin() const
is missing.