Overload () depending on rvalue or lvalue

I have this problem:
I would like to overload () operator in such way, that if it is on the left side it will do something different than when it is on the right side.
For example:
T k;
k(0,0) = 5; - it would dynamically allocate memory of array of size 1x1 and assign number 5

int j = k(1,2) - it should return an error, because memory for k(1,2) hasn't been allocated yet, so there is no value for k(1,2).


Is there a way how to decide whether I'm assigning a value or getting a value? Right now when I overload the operator, it allocates new memory in both cases. So if you have any idea how to do this, please let me know.Thanks.


To my knowledge, you can't do it based on lvalue or rvalue, but you can do it based on const/nonconst:

1
2
3
4
5
6
7
8
9
int& operator () (int,int)
{
 // nonconst -- allocate whatever here
}

int operator() (int,int) const
{
 // const -- don't allocate
}


lvalue will always be nonconst -- although I'm not sure if its reliable that rvalue will always be const. This probably isn't the best way to go about this, and you might want to just make a set/get style approach instead.

EDIT -- fixed syntax (twice)

EDIT -- yeah I just tried this and it doesn't work. Unless the object is explicitly declared as const, it seems to default to the nonconst version, even when an rvalue.

Test program I made:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <conio.h>
#include <iostream>
using namespace std;
class Test
{
public:
    int& operator () ()
    {
        static int v = 0;
        cout << "nonconst called\n";
        return v;
    }

    int operator () () const
    {
        cout << "const called\n";
        return 1;
    }
};

int main()
{
    Test t;
    t() = 5;
    int v = t();

    const Test t2;
    v = t2();

    getch();
    return 0;
}


output:


nonconst called
nonconst called
const called
Last edited on
Hmm..interesting idea. I was also thinking about the get/set approach, but I just didn't like it so much. Funny thing is that when I do it as you wrote, the VS2008 compiler crashes, so I actually can't say whether your idea is working :-). I guess it can't have 2 same overloaded operators that differ only in const (maybe it is also because the operator is of a template class).
Topic archived. No new replies allowed.