2

I'm writing a simple template which stores values in an array checking there's no duplicate.

I overloaded [] operator so it can be used just like a regular array :

T operator [] (int index) { return _array[index]; }

But that doesn't work if I want to directly change values, of course I could write some changeVal(int index, T value) function but it would be fancier if I could use the = operator to do it. Can I overload multiple operators at once ? like :

operator [] = (int index, T val) { _array[index] = val; }

That doesn't compile for me : is there some way to achieve that ?

Apparently I'm the only goon who have thinked of that, or maybe the answer is just hidden inside some of the millions questions with generic sentence like "Overloading operators question" but I won't spend my whole life browsing through those ( did already got quite older doing it ).

Thanks a lot everybody, have a nice day !!!

EDIT : (see below comment) Even if my main problem is solved, an answer to the main question - is it possible and how (even with some trick or whatever) would still be appreciated - that would be quality info for sure !!! Thanks everyone !!!

jj.jpnt
  • 199
  • 1
  • 12
  • 1
    [OT] : Note that if you may change value via `operator []`, you may broke your uniqueness in the array... – Jarod42 Feb 10 '14 at 16:09
  • Very good point !!! I put the check in an add(T e) function, but if as you say if I use [] to change a value, it may need to be checked too... So in the end I would still need to somehow either overload [] and = at once, or detect that the [] overload is used to change the value... does anyone have an idea how to do this ??? – jj.jpnt Feb 10 '14 at 17:31
  • 1
    `operator []` need to return a *Proxy* with `operator =` and implicit cast to `const T&`. – Jarod42 Feb 11 '14 at 10:00
  • Very nice thanks a lot ! If anyone is further interested with all that, found relevant info with previous comment [here](http://stackoverflow.com/questions/20788472/overloading-operator-with-callback) and [here](http://stackoverflow.com/questions/20168543/overloading-assignment-operator-with-subscript-operator) – jj.jpnt Feb 11 '14 at 14:23

1 Answers1

4

If you want to be able to change values, you need to return a reference:

T& operator [] (int index) { return _array[index]; }

It is customary to provide a const version of this operator too:

const T& operator [] (int index) const { return _array[index]; }

That gives you const access to the elements of a const instance.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480