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

David Abrahams dave at boost-consulting.com
Fri Sep 13 00:20:43 CEST 2002

From: "Ralf W. Grosse-Kunstleve" <rwgk at yahoo.com>

> I have just wrapped my first custom C++ iterator with Boost.Python V2.
> The C++ interface is minimal, there is just a default constructor and
> a member function next(). In C++, end of iteration is determined by
> inspecting the state of the result of next().
> Attached is my code for the Python bindings. I feel quite confident
> about my implementation of the binding for next(), but I am a bit
> uncertain about the __iter__ hook:
> 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++
If you had a C++ iterator you could turn it into a Python iterator
automatically using the facilities described in

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).

           David Abrahams * Boost Consulting
dave at boost-consulting.com * http://www.boost-consulting.com

More information about the Cplusplus-sig mailing list