Path: utzoo!utgpu!jarvis.csri.toronto.edu!cs.utexas.edu!usc!apple!voder!procase!roger From: roger@procase.UUCP (Roger H. Scott) Newsgroups: comp.lang.c++ Subject: Re: operator []: ref vs value Message-ID: <91@pascal.procase.UUCP> Date: 27 Feb 90 07:14:52 GMT References: <5216@brazos.Rice.edu> Reply-To: roger@procase.UUCP (Roger H. Scott) Organization: proCASE Corporation, Santa Clara, CA Lines: 63 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? I'm so glad you asked about this! This is one of my favorite C++ inventions. typedef unsigned Index; class SomeType; class SparseVector { public: SparseVector(); SparseVector(unsigned size); ~SparseVector(); ... SparseVectorRef operator[](Index); private: ... // guts friend class SparseVectorRef; void storeAt(Index, SomeType); // implementation of store SomeType at(Index); // implementation of retrieval }; class SparseVectorRef { public: operator SomeType() {return v->at(i);} void operator=(SomeType val) {v->storeAt(i, val);} // other functions, such as operator&(), can be added if you want to // emulate C arrays (for whatever twisted reason) private: friend class SparseVector; SparseVectorRef(SparseVector *vv, Index ii) : v(vv), i(ii) {} SparseVector *v; Index i; }; inline SparseVectorRef SparseVector::operator[](Index i) { return SparseVectorRef(this, i); } void example() { SparseVector v10(10); SomeType a, b; v10[3] = a; // v10.operator[](3).operator=(a); b = v10[7]; // b = v10.operator[](7).operator SomeType(); } Now, wasn't that obvious? ;-]