Actually I would think that operators are used mainly to avoid difficult to spot errors.Sven Schüle wrote:Don't bury this kind of special handling within a standard division operator. Use a normal function for it instead. Otherwise you are creating code which can be hard to understand for others. Special semantics should be visible to the reader if possible.mcostalba wrote:yes typedef of int could be a very good idea, but I would like to intercept divsion by an integer value:I don't think I can do with a typedef .....Code: Select all
// Division must be handled separately for each term inline Score operator/(Score s, int i) { return make_score(mg_value(s) / i, eg_value(s) / i); }
And you are also about to create weird effects somewhere else in the program. Suppose you have an expression "int s = some_value / 2;" and later on you decide to change the type of "some_value" to "Score", what do you expect to happen then? You probably won't notice it (maybe you get a compiler warning which annoys you and you add a cast to int) but the result will be surprising. Using operators can be nice sometimes but this is not a good example IMO.
Sven
In this case it is up to the compiler to check for all the Score variables and divide them in the proper way. If I use a function score_divide() I can miss some place and I can forget some: "int s = some_value / 2;" where some_value is a Score or becomes a Score, according to your example.
If I use a function then "int s = some_value / 2;" will go unoticed and the compiler will do the wrong thing, instead if I use an operator I will be assured that some_value / 2 will be divided correctly as long as _all_ the Score variables have to be divided in that special way (and this is true).
So, although I agree on your starting points, my conclusions seems the opposite
As a bottom line I think use of operators enforces type checking, more then ad hoc functions. So it is not only a "nice" thing but more a "safe" thing to do....of course IMHO.
