operator overloading outside the type

Walter Bright newshound2 at digitalmars.com
Sat Mar 29 06:09:24 UTC 2025


Thank you, Jonathan. You've said it well. Let's give an example:

```
struct A { int a; alias this = a; }

struct B { int b; alias this = b; }

void test()
{
     A a;
     B b;
     int i = a + b;
}
```

This compiles today. The statement is replaced with:
```
     int i = a.a + b.b;
```
Now let's suppose some other module is imported, and it declares:
```
int OpAdd(A a, B b) { return 7; }
```
and now:
```
     int i = 7;
```
Don't we have the classic hijacking problem we've worked hard to avoid in D?

We could lather up with some complicated rules to disambiguate this, but we run 
the risk of becoming C++, where people don't understand how it works and just 
bash at it until it appears to do what they want.

Operator overloading is something that looks great in trivial code snippets, but 
in a complex program they just make it incomprehensible. I've seen enough of that.

To overload operators, just put the overload function in struct A (or struct B) 
where the code reviewer can expect to find it. Not as a freestanding function 
unexpectedly imported from nobody knows where.

The proposal for disallowing overloading operators for the basic types should 
give pause about allowing it for user defined types.


More information about the Digitalmars-d mailing list