Re: using array operators for lvalue and rvalue?
usao wrote:
On May 21, 1:36 pm, Erik Wikstr?m <Erik-wikst...@telia.com> wrote:
On 2008-05-21 22:07, usao wrote:
Does anyone have an example of how to create a class which describes
and array, such that I can use the subscript operator[] on both the
left and right side of an assignment statement? This is as close as I
can get, but I feel it's kludgey and slow...
Perhaps I do not quite understand what you are asking for but something
like this should work:
class Foo
{
int i_;
public:
int& operator[](int i) { return 1; } // Replace 1 with a real element
};
int main()
{
Foo f;
f[1] = 1;
int i = f[1];
}
--
Erik Wikstr?m
So, this can be done without the helper class?
It can if you *don't care* to distinguish between the placement of the
indexing expression on the left of '=' from the right. Of course, since
the operator[] is defined here as non-const, you cannot use it on an
object that is const. Often two operator[] functions are defined, one
const and the other non-const, but used with a non-const object, the
indexing expression will call the non-const version (like in Erik's
program) and not the const version (as some expect).
If you need to distinguish (and call different operator[] functions)
between the use as lvalue and as rvalue:
f[1] = 1;
i = f[1];
then your original solution is essentially the answer. You can make it
a bit more straightforward if you return a proxy in both cases and make
the actual distinction (lvalue vs rvalue) in the assignment operator or
the conversion operator of the proxy, but it's essentially the same.
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask