Xref: utzoo comp.lang.c++:12157 comp.std.c++:722 Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!swrinde!zaphod.mps.ohio-state.edu!rpi!uwm.edu!bionet!agate!ucbvax!dog.ee.lbl.gov!pasteur!galileo.berkeley.edu!jbuck From: jbuck@galileo.berkeley.edu (Joe Buck) Newsgroups: comp.lang.c++,comp.std.c++ Subject: Re: distinguishing operator[] on left and right Message-ID: <11874@pasteur.Berkeley.EDU> Date: 11 Mar 91 18:54:00 GMT References: <1991Mar6.235058.3641@osceola.cs.ucf.edu> Sender: news@pasteur.Berkeley.EDU Reply-To: jbuck@galileo.berkeley.edu (Joe Buck) Lines: 63 In article <1991Mar6.235058.3641@osceola.cs.ucf.edu>, ssd@engr.ucf.edu (Steven S. Dick) writes: |> What if I have a [] operator that does something unusual to extract the |> data from the object... for instance, a bitfield... |> |> // interface parts only... |> class packedbits |> { |> public: |> packedbits(int size); |> int operator[](int index); |> void set(int index); |> void clear(int index); |> }; Your problem is right there. You're having operator[] return an int. This means that it can only be used as an lvalue and cannot be used to set the bit. Let's send a helper class to the rescue: change operator[](int) to return a BitRef helper class: class BitRef { private: packedbits& pb; int index; public: BitRef (packedbits& obj, int idx) : pb(obj), index(idx) {} operator int() { return pb.readBit(index);} BitRef& operator=(int newBit) { if (newBit) pb.set(index); else pb.clear(index); return *this; } }; I need a new function in class packedbits: readBit(int) returns the value of the bit at the given position. Now when I say packedbits bitarray; int x = bitarray[23]; this turns into x = bitarray.readBit(23); and bitarray[34] = x; turns into if (x) bitarray.set(34); else bitarray.clear(34); Note that the returned object acts like a reference to the given bit. In the case where the thing returned is an object, we'd like to be able to redefine operator dot (to have a "smart reference" class). We can't with the ARM, though smart references have been proposed as an extension to the language. -- Joe Buck jbuck@galileo.berkeley.edu {uunet,ucbvax}!galileo.berkeley.edu!jbuck