Xref: utzoo comp.lang.c++:11992 comp.std.c++:672 Path: utzoo!news-server.csri.toronto.edu!cs.utexas.edu!uunet!tut.cis.ohio-state.edu!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: <11634@pasteur.Berkeley.EDU> Date: 4 Mar 91 01:18:46 GMT References: <1991Feb28.212419.20920@ndl.com> <1991Mar2.000705.3496@mathcs.sjsu.edu> Sender: news@pasteur.Berkeley.EDU Reply-To: jbuck@galileo.berkeley.edu.UUCP (Joe Buck) Organization: U.C. Berkeley -- ERL Lines: 45 In article <1991Mar2.000705.3496@mathcs.sjsu.edu> horstman@mathcs.sjsu.edu (Cay Horstmann) writes: >In article <1991Feb28.212419.20920@ndl.com> gilley@ndl.com (Greg Gilley) writes: >>Is there any way to distinguish when the operator[] is used as an >>lvalue as opposed to an rvalue? >> >Surely I am not the first one to propose this one, but here goes anyway. > >Just as pre- and postincrement operator++ are distinguished by a hidden >int argument, could this not be done for lvalue and rvalue operator[]? The difference is that it was needed for ++; there is otherwise no way to tell the difference between predecrement and postdecrement, so you couldn't make smart pointer classes look like pointers. However, it's not difficult at all to get the proper behavior from the existing language with operator[]. If you want to get a different operation when the result of operator[] is used as an rvalue than you do when it is used as an lvalue, you can have operator[] return a special class that has both an assignment operator (which is used in the lvalue case) and a cast operator (which is used in the rvalue case). >Points to consider: > (1) It is ugly as hell > (2) It has precedent (operator++) I disagree that this is a precedent. There was no way before to tell ++p from p++ where p is a class. It's not difficult at all to handle v[key] = x, and x = v[key] correctly where v[key] is, say, a hash table and key is a key, and the entry for key may or may not exist. I take it this is a case where you think there is a problem that needs to be solved by a language extension. But there is no problem, and the code to do it right is less ugly than your method. > (3) It won't break existing code > (4) It does not use the keyword "static" in unusual ways. (5) It is completely unnecessary (6) It will lead to people making other unnecessary "extensions" because there are other analogous situations that people will think need "solutions" -- -- Joe Buck jbuck@galileo.berkeley.edu {uunet,ucbvax}!galileo.berkeley.edu!jbuck