I’m considering a “map of maps” type, and wonder if it would be considered bad practice to have two operator[]s, with different parameters having different meaning. Suppose the “outer” map is indexed by OuterKeyType and the inner maps by InnerKeyType, and we have an object of the “map of maps” m. Then the behaviour would be that m[OuterKeyType] would return (a reference to) the entire inner map indexed by that key, while m[InnerKeyType] would return a compound formed by some operation across all the maps on the element indexed (it can be assumed all the maps have the same set of keys).
So, is this design counterintuitive and bad, or is it just convenient and thus good?
The first thing is that it is a really bad idea in general to hide different behaviors under the same function name just by the operands that are being passed. It makes it hard to determine what logic will be triggered when you encounter
obj[value], as it will have completely different behavior depending on whatvalueis, which might or not be visible while reading this code.I would recommend that you provide named functions for the operations, just because you can overload an operator it does not mean that you should. Depending on the domain the functions would have different names:
obj.getX(value)andobj.getY(value)are much easier to understand provided thatXandYare sensible names.