Operator overloading through UFCS doesn't work

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue May 31 08:18:20 PDT 2016


On Tuesday, May 31, 2016 14:11:58 ixid via Digitalmars-d-learn wrote:
> On Sunday, 29 May 2016 at 07:18:10 UTC, Jonathan M Davis wrote:
> > And the fact that allowing free functions to overload operators
> > via UFCS sends us into that territory just highlights the fact
> > that they're a horrible idea.
> >
> > - Jonathan M Davis
>
> Do you have any examples of UFCS doing bad things? Most people
> seem to very much like it yet you argue against any change that
> would benefit UFCS.
>
> You seem to prefer:
>
>      read(to(easier(much(i)))) over i.much.easier.to.read

The primary benefit of UFCS is that you can write generic code that will
work with both member functions and free functions, allowing you to have a
free function that does something and a member function that does that same
thing more efficiently for that specific type (a prime example of this would
be a function like find where a linear search make sense in most cases but
wouldn't for certain data structures - e.g. a sorted, binary tree). So, the
"universal" aspect of UFCS is important for generic code, whereas it would
be completely unnecessary if the code weren't generic. All of the other
benefits of UFCS are highly subjective and have to do with what a particular
person thinks is easier or harder to read rather than actual, technical
benefits (though obviously writing code in a way that is easier to read for
those working on it is obviously valuable). Personally, I've dealt with
functional languages enough that I've never felt that UFCS was much of an
improvement syntactically. But we have it, and anyone is free to use it or
not as they see fit.

Regardless, what I'm arguing against here is altering operator overloading
so that it works with free functions via UFCS instead of requiring that it
be part of the type. It's a terrible idea IMHO to allow random code to add
an overloaded operator to a type rather having it actually be part of the
type's design, and in addition to that, it doesn't play at all nicely with
symbol conflicts, because you're using an operator rather than a function,
meaning that not only do you have no way to specify which version of the
overloaded operator code should use, but it would completely defeat the
purpose of using an overloaded operator in the first place even if you
could. But fortunately, Walter agrees with me (or at least did, the last
time the subject came up in the newsgroup), so I don't think that I have to
worry about overloaded operators be definable via free functions.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list