[C++-sig] Re: Howto wrap operator[]? (boost::python)
David Abrahams
dave at boost-consulting.com
Sat Jun 14 12:24:49 CEST 2003
"Joel de Guzman" <djowel at gmx.co.uk> writes:
> 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):
>
> [snip]
>
>> 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).
But note that the OP was wrapping a container of double, which isn't
subject to many of the same problems.
> 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
> easier.
The "easier" part will be a big help for everyone.
--
Dave Abrahams
Boost Consulting
www.boost-consulting.com
More information about the Cplusplus-sig
mailing list