Not allowed to globally overload operators?

Tejas notrealemail at gmail.com
Tue Jul 20 06:20:34 UTC 2021


The following doesn't work:
```d
import std;
int opBinary(string s:"+")(int a, int b){
     int result;
     a<b?(result = -1):a>b? (result = 1): (result = 0);
     return result;
}
void main(){
     int f = 1 + 5;
     writeln(f);
}
```
It outputs 6

But if I manually write it as
```d
int f = opBinary!"+"(1,5);
```
It works as expected.

Why isn't it working by default?

Initially, I was trying to create the spaceship operator of C++, 
but we aren't allowed to create new operators, it seems. Then I 
just wanted to verify whether we can even overload an operator 
globally, but even that seems to be failing, atleast for me.


More information about the Digitalmars-d-learn mailing list