operator overloading outside the type
Walter Bright
newshound2 at digitalmars.com
Sat Mar 29 06:33:16 UTC 2025
On 3/28/2025 8:01 PM, Steven Schveighoffer wrote:
> You can call the operator, it's just a normal function.
>
> ```d
> a.opBinary!"+"(b);
> ```
I understand that operators can be regarded as just syntactic sugar for
functions. To a computer, they are. But to a human, they are not.
Do remember we had a great debate long ago about how symbol lookups were done?
```
int test(int printf)
{
import core.stdc.stdio;
return printf + 1;
}
```
and this did not work because the lookup went from inner scopes to outer scopes,
and would pick up the printf in core.stdc.stdio instead of the parameter? To me,
that lookup was the obvious way to go, it was simple and completely consistent.
But everybody told me it was intuitively wrong. Eventually, we moved to a
two-pass symbol lookup system. (I bet hardly anybody knows that, because human
intuition is different.) I had the same issues years before when designing human
interfaces.
People have different intuitions about operators than they do about functions.
Don't fall into the trap that I did. Operators are not functions, they are
special. People have baked in expectations about their behavior. They have
things like operator precedence. (Languages that try to remove operator
precedence never caught on.)
You bring up a good point with ImportC. C structs don't have operator
overloading, and you want to add arithmetic operator overloading for those
structs. I don't know what the raylib Vector2 struct looks like, but I bet it's
just a few declarations. It probably does not change from one version of raylib
to the next - so you could just copy-paste it into D, adding the operator overloads.
Your idea of wrapping it and unwrapping it is also a good one. Perhaps `alias
this` can make it more convenient? Or adding a shim?
More information about the Digitalmars-d
mailing list