4 ms·
Only if you know what + happens to mean. Which, it turns out, you sometimes don't. It's especially bad when you think you know what it means, but you're mista
by metafunctor 5y ago
Only if you know what + happens to mean.
Which, it turns out, you sometimes don't. It's especially bad when you think you know what it means, but you're mistaken.
I was kind of joking, of course, but only kind of. I'm a happy user of operator overloading.
- maleldil 5y agoI don't see how that's any different from normal method calls, though. If you don't know what `a + b` does for an arbitrary type, why would you know what `a.add(b)` does? Overloaded operators and methods are all just operations on a type.
- tialaramex 5y agoConvention. Like the core of language itself. If you refuse to respect convention we can't communicate. You ask about a.add(b) but notice that's also using two operators. First it needs a . operator for member access. Languages rarely allow you to overload this operator because doing so makes your head hurt, but there's no reason in theory it couldn't exist. [In Python we can use __getattribute__ to meddle with this, but to avoid infinite recursion we can't use __getattribute__ to meddle with the operator overloading, such as __getattribute__ itself... ] Second you need a () operator to call the member. This you can sometimes overload, for example in C++. So what this does might be defined by that operator overload. The only way to avoid this being too confusing to use is to obey conventions, and even once you do that many of the operator overloads will be rarely needed and one wonders whether to just abolish overloading them. Worse, unlike a function call, operators sometimes come with other semantic expectations that may be impossible to enforce. For example the operators && and || are short-cutting logic booleans, in almost any programming language with such an operator, in_cache(foo) || slow_check(foo) only performs slow_check(foo) when in_cache(foo) was false. But an overload can't ensure this! Instead both will be evaluated and the results provided to the operator overload function, too late to optimise. Overloading should be used very sparingly. If any significant fraction of your users find your overload confusing, it was a bad idea. Better than ten people wonder why they must write a.add(b) than that one person writes a + b and then is completely astonished by what you decided that does.