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]
wou开发者_如何学运维ld 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 what value
is, 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)
and obj.getY(value)
are much easier to understand provided that X
and Y
are sensible names.
As this tutorial states, you should not overload the operator []
but the operator ()
. It is more safe, faster and C++ish than the C "array of array" operator.
精彩评论