I want to overload the square bracket operator [] using a private nested class to differentiate between v[i] = val and val = v[i]
Asked
Active
Viewed 234 times
-2
-
2And which one should be called if you write `val2 = v[i] = val1`? – CompuChip Feb 18 '14 at 08:43
-
2Good for you. What have you tried so far, and what problems did you encounter? – Angew is no longer proud of SO Feb 18 '14 at 08:44
-
If it's a private nested class anyway, why not just provide methods whose names _clearly_ describe the (side-)effects, rather than some obscure what-this-does-depends-on-where-you-put-it behavior? – CompuChip Feb 18 '14 at 08:45
-
1So do it. It's a frequently used idiom. – James Kanze Feb 18 '14 at 08:53
-
If you're asking what the class needs to do, then you need an assignment operator for the first, and a conversion operator for the second. If you're asking something else, then please ask your question in the form of a question. – Mike Seymour Feb 18 '14 at 08:57
1 Answers
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
-
2No, 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