operator overloading outside the type
sfp
sfp at hush.ai
Sat Mar 29 19:24:36 UTC 2025
On Saturday, 29 March 2025 at 18:48:04 UTC, Walter Bright wrote:
> On 3/29/2025 9:25 AM, Timon Gehr wrote:
>> Yes. UFCS never overrides a matching member function, no
>> matter how well the UFCS function matches. UFCS is not even
>> attempted if a call can be resolved via member function.
>
> That's correct. The issue brought up in my preceding post is
> *should* operators be treated as if they were functions? Or are
> they special? I've seen what happens when they are treated as
> functions. People write code that looks like conventional C++
> code, but with the operators overloaded to do something utterly
> different. They'd write articles saying how cool this was. I
> had the opposite reaction.
There's nothing preventing people from writing incomprehensible
"operator madness"-style code in D. Whether or not `+` behaves
like addition is up to the programmer, and where the function
`opBinary!"+"` is defined is immaterial.
> There are a number of deliberate characteristics in D that
> discourage writing incomprehensible code, like no macros and no
> version algebra. The operator overloading capability in D is
> deliberately restrictive, to make it harder to do
> non-arithmetic things with it.
```
import std.stdio;
struct Number {
void opBinary(string op : "+")(Number other) {
writeln("egads");
}
}
void main() {
Number x;
Number y;
x + y;
}
```
> With functions, there are no implicit expectation of what is
> does, we all know that. But the expectation with operators is
> `a+b` does an addition. (That's why D uses ~ for concatenation,
> not +) If the user suspects that it does something else, at
> least he can visit the type declaration to see if it was
> repurposed.
Open debugger, step into `a+b`. Problem solved.
> But overloading operators with freestanding functions? It
> becomes a nightmare with non-trivial programs.
For the highly nontrivial code that I write, being able to define
operators as free functions would make my code simpler. Being
forced to define them as member functions results in ugly,
tortured code. I think Herb Sutter said something about functions
wanting to be free...
More information about the Digitalmars-d
mailing list