-1

I want to overload "[]" witch is used to access array

But I also want to separate read/write to do different thing

For example :

class myclass{
private:
    int val;
public:
    myclass(){val=0;}
    myclass(int _in){val=_in;}
    ....
    //for A=myclass[n]
    myclass& operator[](int index){
        ...
        return 
    }
    //for myclass[n]=B
    myclass& operator[](int index){
        ...
        return 
    }
}
Moriarty
  • 9
  • 3
  • 3
    You might have const/non-const version which is different than read/write version. – Jarod42 Jul 19 '21 at 13:56
  • 2
    This looks like something you could accomplish by returning a proxy – IWonderWhatThisAPIDoes Jul 19 '21 at 14:00
  • 3
    The problem is you are doing read/write not to the `operator[]` but to result of that. So you would have to write a class which would be returned by `operator[]` and act accordingly when read from and written to. – Slava Jul 19 '21 at 14:00
  • 2
    Very related/dupe: https://stackoverflow.com/questions/54292588/how-to-overload-the-operators-to-call-a-setter-function-on-an-operator-call – NathanOliver Jul 19 '21 at 14:00
  • Assuming you want two overloads to have the same argument type (`int` in your case) It is possible to overload `operator[]()` for `const` (which cannot change (non-mutable) members of `myclass` nor return a non-`const` reference to a member of `myclass`) and non-`const` (which is able to change members of `myclass`). It is also possible to overload `operator[]()` for different argument types (e.g. an `int` and a `std::string`, if such usage makes sense for your class). – Peter Jul 19 '21 at 14:03
  • There may be a misunderstanding in your question that will prevent effective answers. Is `myclass` supposed to behave like an array? Or is it a type that you expect to put in standard arrays? Having `myclass::operator[]` return `myclass&` is unusual enough to suspect that there's a misunderstanding. – Drew Dormann Jul 19 '21 at 14:23
  • You could do `struct Read{}; struct Write{};` as tags, and then `myclass& operator[](pair x);` and `myclass& operator[](pair x);` which would be called `m[{Read{}, 5}]` or `m[{Write{}, 5}];` ... but all that rigamarole you might be better off having `read()` and `write()` methods instead. – Eljay Jul 19 '21 at 15:13
  • I ask this question is because I want to do something behave like [ORAM](https://en.wikipedia.org/wiki/Oblivious_RAM) , which read is search whole index of array and return it , and write will overwrite whole array when writing – Moriarty Jul 20 '21 at 02:45

1 Answers1

0

The chosen operator overload is affected solely by the type of the operands, and not how you use the returned value. There can only be one overload for one pair of operands.

However, you can use a return value that behaves one way when used as left hand operand of assignment, and another way when used as right hand operand.

eerorika
  • 232,697
  • 12
  • 197
  • 326