Operator overloading through UFCS doesn't work

Artur Skawina art.08.09 at gmail.com
Wed Oct 17 03:24:17 PDT 2012


On 10/16/12 17:57, Maxim Fomin wrote:
> This doesn't scale well. Certanly, nobody would intentionally create problems. But if you import code of other people, whom you cannot control, override problems occurs.
> 
> At NG discussion it may look nice to define some type and then add operator overloading methods but as soon as you import some other modules, authors of which also consider UFCS operators a good idea, everything breaks including namespace conflict as well as loosing ability to manipulate that type within built-in expression as well.

Operator overloading can be abused - that's an obvious and well known fact. But that
same feature can also be very useful, if used right. Worrying about UFCS problems in
the context of op-overloading needlessly complicates the issue - the UFCS problems are
there also w/o op-overloads.

UFCS is, like a lot of D features, just a quick hack, that somebody thought was "cute"
enough to add to the language, w/o really considering the consequences. It might be
possible to make UFCS solid enough, but introducing a lot of special-casing isn't the
right way.

For example, UFCS will allow you to write a templated generic function (or new type)
that works with any type providing a certain interface (function signatures in this
case) and "fills in" missing optional methods, w/o cluttering the code or wrapping the
methods, right? Wrong, as UFCS is (wrongly) restricted to module-scope functions, hence
can't be used for this. UFCS is nothing but syntax sugar (you can do 'f(o)' everywhere
where UFCS would let you do 'o.f()'). Similarly as in the op-overload case - if the
argument is that lifting the restriction would allow for confusing code (methods
being available in one scope, but not another; or 'o.f()' doing different things in
different scopes) then that's an argument for *removing UFCS* - as the same problems
happen elsewhere too (think two modules each containing a different 'f(o)' function
definition and several scopes that locally import just one of the modules).

Things would be a bit different if D had a "global" scope, but that would also add new
issues, and UFCS alone does not justify introducing one. (It wouldn't even help UFCS
much, other than reducing the chances of clashing method names)

artur


More information about the Digitalmars-d-learn mailing list