Path: utzoo!utgpu!news-server.csri.toronto.edu!rutgers!att!cbnews!cbnewsm!gregk From: gregk@cbnewsm.att.com (gregory.p.kochanski) Newsgroups: comp.lang.c++ Subject: Re: Better soln than fn resolution based on const-ness of return type Message-ID: <1990Dec4.231722.10425@cbnewsm.att.com> Date: 4 Dec 90 23:17:22 GMT References: <814@atcmpe.atcmp.nl> <535@taumet.com> Distribution: usa Organization: AT&T Bell Laboratories Lines: 43 In article , cline@cheetah.ece.clarkson.edu (Marshall Cline) writes: > Allow me to propose a simpler and more comprehensive solution than resolving > funcalls based on the const-ness of their return types. Consider a returned > reference from an `inspector' such as int& operator[](int). The general > problem is to `capture' how this returned reference is used in the *caller's* > context. The poster wanted to differentiate between `accessing the value of' > and `used in LHS of an assignment operator', as exemplified by > arr[0] = arr[1]; > ^^^^^^----suppose this can be done quickly > ^^^^^^-------------and suppose this is more expensive > > The cleaner solution to this more general problem is to return a light-weight > object which simulates a reference. > > class intRef { > int& ref; > public: > intRef& operator=(int x) { expensive_check(x); ref=x; return *this; } > operator int() { return ref; } //access is cheap > IntRef(int& r) : ref(r) { } > }; This *is* nice (and probably is the way to go), but 1) you also have to define += -= *= /= |= <<= ... and the address operator, in order to make it a reasonable simulation. 2) Many practical situations will require a class which has more than just a reference. You may also need pointers to the original array, and perhaps a second (or third...) subscript. A three-dimensional array needs *three* helper classes. Real life situations (real life for numeric computations, that is) can end up with a substantial amount of overhead. If your calculations already take hours, even relatively small amounts of overhead (like copying a 3 member structure and a pointer operation) can be painful. 3) It does lead to a proliferation of trivial helper classes which could easily make your code totally unintelligible. Especially in higher dimensional cases. 4) It's not quite a perfect simulation, because you can only have one user-defined conversion, which is used up in converting from intRef to int. If you have a user-defined conversion from int to SomethingElse, it will have to be explicitly called. Greg Kochanski gpk@att.physics.com AT&T Physics Research... Physics for fun and profit. Brought to you by Super Global Mega Corp .com