[C++-sig] Howto wrap operator[]? (boost::python)

Joel de Guzman djowel at gmx.co.uk
Sat Jun 14 06:10:40 CEST 2003

Nicodemus wrote:

> Currently you will have to expose them by hand. Python has two
> especial methods, named __setitem__ and __getitem__, that allows a
> class to 
> define the behaviour of the [] operator. All you have to do is export
> this especial methods as members of your class. Here is some code
> (untested):


> template <class T>
> T vector_getitem(std::vector<T> &v, int index)

FYI, I am currently working on a solution to get this working properly.
The problem with the code above, as Dave mentioned in a separate
thread (and a problem that I am facing right now) is that if the returned
item is by value, it has no link to the original element in the vector. If
for example T has a non-const member function, say "set(int)", we run
into problems like:

    >>> vec[n].set(v)

where we are trying to set v of a temporary T, thus making the vector
elements through the [] operator immutable except through assignment 
(through __setitem__):

    >> vec[n] = vec[n].set(v)

It might be tempting to return a reference. OTOH, we are in danger
of dangling references once the vector changes (resizes for instance).
I'm now experimenting with some wrapper code to fix this situation
while at the same time making the wrapping of __getitem__ and its friends

Joel de Guzman
joel at boost-consulting.com

More information about the Cplusplus-sig mailing list