operator overloading outside the type
Jonathan M Davis
newsgroup.d at jmdavisprog.com
Sat Mar 29 03:52:17 UTC 2025
On Friday, March 28, 2025 5:27:47 PM MDT Timon Gehr via Digitalmars-d wrote:
> On 3/28/25 21:54, Jonathan M Davis wrote:
> > How overloaded operators do or don't work with a type are a core part of its
> > design and affect how it interacts with the language in general, including
> > how it interacts with language features, whereas a normal function isn't
> > anything special and isn't treated by the language in any special way.
>
> The proposal is not to somehow add the operators to the type using an
> external declaration, just to allow the standard syntax sugar to be used
> to call these functions via UFCS.
Yes, and part of my point is that for a number of operators, that's a
problem, because it would mean trying to overload the default behavior of an
operator via a symbol which may or may not be imported. Maybe it would be
okay with something like the arithmetic operators, but for something like
toHash or opCast, it could cause serious problems.
For at least some of these operators, the language is designed with the idea
that they are either always present, or the compiler will generate code on
its own to use them if they're not, and those absolutely must be part of the
type, or we'll get all kinds of iconsistencies and hard-to-track-down
behaviors. Trying to have them be external would be like trying to have copy
constructors declared externally and be affected by imports.
The only cases where it might make sense to allow overloaded operators to be
defined externally are those where the compiler doesn't even allow them to
be used if they haven't been explicitly declared for that type, because then
they arguably are just syntactic sugar at that point. I still don't agree
with the idea in those cases, but if they're not actually overriding
anything, then the only conflicts should be akin to what you get with UFCS.
However, for any operator which has built-in behavior, allowing them to be
overloaded will either simply not work, or it will allow for some pretty
nasty bugs. I sure don't want to have to deal with what happens if we try to
allow for something like opEquals or opCast to be overloaded externally.
- Jonathan M Davis
More information about the Digitalmars-d
mailing list