Shortcomings of D-Style Fused Operator Overloading

Jonathan M Davis newsgroup.d at jmdavisprog.com
Fri Jul 7 16:37:26 UTC 2023


On Friday, July 7, 2023 10:18:56 AM MDT deadalnix via Digitalmars-d wrote:
> On Friday, 7 July 2023 at 09:18:38 UTC, Ahmet Sait wrote:
> > Let's define two intervals x and y:
> > {x ∈ ℝ │ a ≤ x ≤ b}
> > {y ∈ ℝ │ c ≤ y ≤ d}
> >
> > And the inequality operators:
> > ```
> > x < y = ⎧ 1  if b < c
> >
> >         ⎨
> >         ⎩ 0  otherwise
> >
> > x ≤ y = ⎧ 1  if b ≤ c
> >
> >         ⎨
> >         ⎩ 0  otherwise
> >
> > x > y = ⎧ 1  if a > d
> >
> >         ⎨
> >         ⎩ 0  otherwise
> >
> > x ≥ y = ⎧ 1  if a ≥ d
> >
> >         ⎨
> >         ⎩ 0  otherwise
> >
> > ```
> >
> > Exercise: Write an `opCmp()` method that implements the rules
> > above for `struct Interval { int lower, upper; }`. (Hint: It's
> > not possible.)
>
> Thanks god. If you are doing something non standard, do not use
> the builtin operators, give you operation an explicit name.

Yeah. The limitations on opCmp are very much on purpose. We already arguably
have issues due to how the comparison operations work with NaN (it's a
useful feature, but it does potentially cause problems with generic code).
The comparison operators are very much intended to work in the standard
manner even on user-defined types, and types where that isn't going to work
should be using a different set of functions.

Operator overloading in general is provided so that user-defined types can
be used like built-in types and work with generic code that uses those
operators. Domain-specific language stuff should probably be left to either
a domain-specific language or just use properly named functions. Trying to
alter the built-in operators to operate in a way that differs like this from
the built-in types is arguably an abuse of operator overloading.

So, while obviously, if someone is looking to do this like they might have
done in C++, that can be annoying for them, it's really not something that D
is looking to support.

- Jonathan M Davis






More information about the Digitalmars-d mailing list