Tsoding streamed about D
Steven Schveighoffer
schveiguy at gmail.com
Wed Mar 19 11:37:21 UTC 2025
On Wednesday, 19 March 2025 at 06:05:24 UTC, Manu wrote:
> On Wed, 19 Mar 2025 at 11:36, Meta via Digitalmars-d < Why
> didn't his operator overloading experiment work?
>
> struct S {
> int x;
> }
>
> // non-member opBinary
> S opBinary(string s : "+")(S lh, S rh) {
> return S(lh.x + rh.x);
> }
>
> void main()
> {
> S a, b;
> S s1 = a.opBinary!"+"(b); // <- UFCS works, as expected
> S s2 = a + b; // ERROR: doesn't work! why not? the rewrite
> should work
> via UFCS as above...
> }
>
> I can't imagine any good reason his experiment should have
> failed. I would want this too when extern to a C lib; it hasn't
> come up for me before, but if it did, I would log a bug
> instantly.
operator overloads must be member functions.
I think this fits into Walter's vision that you should not be
able to abuse operator overloads to build your own semantics with
already-defined types.
e.g. you shouldn't be able to define `a + b` to be something
other than what `a` or `b` intended.
This already is allowed via UFCS, I guess Walter thinks operator
overloads are more intimate for the types.
Take note that UFCS did not exist for D1 ([except for
arrays](https://digitalmars.com/d/1.0/arrays.html#func-as-property)), so this vision was more consistent back then.
I don't know if this is one of those "will never happen" stances,
or "maybe I can be convinced" stances.
-Steve
More information about the Digitalmars-d
mailing list