operator overloading outside the type
sfp
sfp at hush.ai
Sat Mar 29 16:08:40 UTC 2025
On Saturday, 29 March 2025 at 06:09:24 UTC, Walter Bright wrote:
>
> [...]
>
> Don't we have the classic hijacking problem we've worked hard
> to avoid in D?
I wasn't sure about this, so I wrote up my own similar test.
```
// bad.d
module bad;
import std.stdio;
auto add(S, T)(S a, T b) {
writeln("bad add");
return a.i + b.i;
}
// main.d
import std.stdio;
import bad;
struct A { int i; }
struct B { int i; }
int add(A a, B b) {
writeln("good add");
return a.i + b.i;
}
void main() {
auto a = A(1);
auto b = B(1);
add(a, b); // prints "good add"
bad.add(a, b); // prints "bad add"
}
```
This is a little different since it doesn't use `alias this`---I
haven't used this feature much and can't speak to how it would
affect any of this. Anyway, my example is closer to my own use
case... e.g. just replace `add` with `opBinary!"+"`.
I wasn't sure what to expect with the example above, but I think
its behavior is nice and predictable. There doesn't seem to be
any "hijacking" of the sort described by you and Jonathan, anyway.
More information about the Digitalmars-d
mailing list