[C++-sig] wrapping a custom C++ iterator

Ralf W. Grosse-Kunstleve rwgk at yahoo.com
Fri Sep 13 18:32:32 CEST 2002


--- David Abrahams <dave at boost-consulting.com> wrote:
> > 1.
> >     static w_t& iter(w_t& o) { return o; }
> >
> > 2.
> >         .def("__iter__", iter, return_internal_reference<>())
> >
> > This works, but is it the right approach?
> 
> I guess it's fine, but it doesn't use the built-in support for C++
> iterators.
> If you had a C++ iterator you could turn it into a Python iterator
> automatically using the facilities described in
> libs/python/doc/v2/iterator.html.

I looked at this before and came to the conclusion that I'd have to refactor my
class to make it suitable for use with the built-in iterator support (I have no
iterator typedefs, no begin, no end, no operator++). This is not really
something I'd like to do.

> Well, technically it's not quite right, since __iter__ on an iterator type
> is supposed to return the same object, and what you're doing returns a new
> object (which wraps a reference to the same C++ object).

OK, thanks for pointing this out! I changed my code:

1.
    static boost::python::object iter(boost::python::object const& o)
    {
      return o;
    }

2.
        .def("__iter__", iter)
    
In Python this works now:

  i = sgtbx.space_group_symbol_iterator()
  assert id(i) == id(iter(i))

Is this approach technically OK?

Ralf


__________________________________________________
Do you Yahoo!?
Yahoo! News - Today's headlines
http://news.yahoo.com




More information about the Cplusplus-sig mailing list