-2

I want to overload the square bracket operator [] using a private nested class to differentiate between v[i] = val and val = v[i]

1 Answers1

0

You don't need a private nested class to distinguish these cases. Just make one const.

 public:
     T& operator[](size_t index);
     const T& operator[](size_t index) const;

If you do this, the const variant will be used in the const right-hand side case and the non-const one will be used when assigning to the element on the left-hand side.

Michael Aaron Safyan
  • 93,612
  • 16
  • 138
  • 200
  • 2
    No, that distinguishes between whether or not it's applied to a `const` object, not whether or not the return value is assigned to. – Mike Seymour Feb 18 '14 at 08:53
  • @MikeSeymour, right, that's why I said "const" right-hand side. (If the right-hand side is non-const, the non-const variant will be used). But I imagine that this is what the OP really needs. – Michael Aaron Safyan Feb 18 '14 at 08:57
  • No, that wouldn't work, because there could be a `const` or non-`const` instance on the RHS of the assignment. – juanchopanza Feb 18 '14 at 09:43