Boost logo

Boost Users :

From: David Abrahams (dave_at_[hidden])
Date: 2003-07-08 09:21:01


Tim Robertson <timr_at_[hidden]> writes:

> Hi,
>
> I've been trying to get indirect_iterator working in what seems (to me)
> to be a straightforward context -- I have a std::vector of
> boost::shared_ptr objects

Doesn't work; we know about it. There's a new version of
iterator_adaptors in the Boost CVS which fixes this problem. The
interface is different, but you're best off using the new one anyway
because the old one will expire with the next Boost release.

> and I need both const and non-const iterators
> into the vector (I'm using the vector as the sole data member of a
> container class, and I need the iterators to properly handle const and
> non-const container types).

Whether or not this will work depends on what you mean by "correctly".

> This looks something like this:
>
> class MyClass
> {
> // ...
> };
>
> class MyContainer
> {
> public:
> typedef MyClass value_type;
> typedef value_type & reference;
> typedef value_type * pointer;
> // and so on, for const_reference, const_pointer, etc...
>
> // ...
>
> private:
> std::vector<boost::shared_ptr<MyClass> > _data;
> };
>
> Now, the trouble comes when I attempt to define the iterators for
> MyContainer using the indirect_iterator generators. If I do the obvious:
>
> Approach #1:
> ------------
>
> typedef indirect_iterator_pair_generator<
> vector<shared_ptr<MyClass> >::iterator,
> value_type, reference, const_reference,
> std::random_access_iterator_tag,
> pointer, const_pointer>::itgen;
>
> typedef typename itgen::iterator my_iterator;
> typedef typename itgen::const_iterator my_const_iterator;
>
>
> I find that the const_iterator generated is inadequate for use in a
> container context. Particularly, it produces a my_const_iterator that
> has the following constructor signature:
>
> my_const_iterator(shared_ptr<MyClass> *)
>
> Whereas, a const std::vector<shared_ptr<MyClass> > will produce
> const_iterators that look like this:
>
> const shared_ptr<MyClass> * const

No, the last const cannot be part of the type of any const_iterator,
because then it wouldn't be incrementable. Also, vector iterators
need not be pointers, but that may not be important to your problem.

> This causes compilation problems, because inevitably, in this context,
> you'll want to construct a my_const_iterator from a vector::const_iterator.
>
> The problem seems obvious: the indirect_iterator_pair_generator class
> is considering only non-const base iterators.

Please try the CVS iterator adaptors and get back to us.

-- 
Dave Abrahams
Boost Consulting
www.boost-consulting.com

Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net