[C++-sig] Re: operator[]
David Abrahams
david.abrahams at rcn.com
Thu Apr 25 15:17:57 CEST 2002
__getitem__ can be used directly, but the signature for __setitem__ is:
__setitem__(self, key, value):
so you need a wrapper function:
template <class Self, class Key, class Value>
setitem(Self& self, Key const& key, Value const& value)
{
self[key] = value;
}
...
.def("__setitem__", &setitem<Vector2d,int,double>)
----- Original Message -----
From: "chuzo okuda" <okuda1 at llnl.gov>
To: "David Abrahams" <david.abrahams at rcn.com>
Cc: "Martin Casado" <casado2 at llnl.gov>; "Susan Hazlett"
<shazlett at llnl.gov>; "Kathleen McCandless" <mccandless2 at llnl.gov>
Sent: Wednesday, April 24, 2002 7:38 PM
Subject: operator[]
> Dave,
> Now, I have problem with operator[].
>
> class Vector2d {
> public:
> Vector2d():x(0.0),y(0.0) {}
> Vector2d(const double xval, const double yval): x(xval),y(yval) {}
> ~Vector2d() {}
> double getX() {return x;}
> double getY() {return y;}
> double& operator[](int i) {return i==0 ? x : y;}
>
> protected:
> double x, y;
> };
>
> int main(int argc, char** argv) {
> Vector2d v = Vector2d(1.0,2.0);
> cout << v[0] << "; " << v[1] << endl;
> v[0] = 5.0; v[1] = 9.0;
> cout << v[0] << "; " << v[1] << endl;
> }
>
> And operator[] in C++ support both read and write operation.
> It is not clear how to write "__setitem__" and "__getitem__" like:
>
> .def("__setitem__", &Vector2d::operator[])
> .def("__getitem__", &Vector2d::operator[])
More information about the Cplusplus-sig
mailing list