Path: utzoo!utgpu!jarvis.csri.toronto.edu!cs.utexas.edu!tut.cis.ohio-state.edu!zaphod.mps.ohio-state.edu!rpi!brutus.cs.uiuc.edu!apple!agate!saturn!daniel From: daniel@saturn.ucsc.edu (Daniel Edelson) Newsgroups: comp.lang.c++ Subject: Re: operator []: ref vs value Message-ID: <10844@saturn.ucsc.edu> Date: 22 Feb 90 18:31:07 GMT References: <5216@brazos.Rice.edu> Reply-To: daniel@saturn.ucsc.edu (Daniel Edelson) Organization: University of California, Santa Cruz Lines: 45 In article <5216@brazos.Rice.edu> dougm@zamenhof.rice.edu (Doug Moore) writes: > >I can't seem to find a way to do precisely what I want; I want a >sparse vector data type. I can declare a float-returning operator [] >that returns 0.0 if the array index corresponds to a row for which no >nonzero is stored. I can declare a reference-to-float-returning >operator[] that creates a new entry in my linked list of nonzero >values when the row has no corresponding nonzero stored. >Unfortunately, I want one behavior when the pseudo-array access occurs >as an rvalue and another when it appears as an lvalue. Can I get what >I want? > >Dougm You can have the [] operator return a dummy type and then overload the assignment operator on the dummy type. This is not real efficient but it seems to give correct semantics. I wrote this code for reference counting vectors efficiently, but its not efficient. It should work for sparse vectors well, though. class vector; struct dummy { // A dummy refers to a specific vector element vector * vp; int index; operator int&() { /* return the element value */} void operator=(int & t); dummy(vector *vvpp, int i) : vp(vvpp), index(i) { } }; struct vec { // implementation details are yours dummy & operator[](int index) { return dummy(this, index); } }; inline void dummy::operator=(int & t) { // Do whatever necessary to assign t to the vector // component at index in *vp. } daniel@cis.ucsc.edu daniel edelson