Operator overloading through UFCS doesn't work

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed May 25 23:23:17 PDT 2016


On Wednesday, May 25, 2016 23:31:18 Elie Morisse via Digitalmars-d-learn 
wrote:
> On Wednesday, 25 May 2016 at 21:50:06 UTC, Jonathan M Davis wrote:
> > It's not an overloaded operator anymore at that point, and that
> > definitely fails to work for generic code, since not all
> > operators are overloaded operators. Free functions don't have
> > that problem.
>
> Sorry to reiterate the previous post but is that really the case?
>
>    void FuncTemplate(...)(...) {
>      X.FreeFunc(Y);
>    }
>
>    import ModuleA; // contains FreeFunc
>    import ModuleB; // contains a conflicting FreeFunc overload
>
>    FuncTemplate!()(); // fails
>
> Where is the difference with writing generic code with operators
> (overloaded or not)?

The difference is that it's impossible to do 10.opBinary!"+"(15), so if
you're forced to do foo.opBinary!"+"(bar) to get around a symbol conflict,
it won't work with built-in types. UFCS does not have that problem, because
you're dealing with free functions and can choose to not use UFCS and
provide the full import path or to alias the function, which you can't do
with operators - particularly built-in operators.

D was designed to be much cleaner with operator overloading than C++ is. It
restricts what the definitions of the operators are so that you don't have
to define as many of them to get the basic operations (e.g. opCmp for most
of the comparison operators or op!"++" for both pre-increment and
post-increment) and so that they aren't easily overloaded to do stuff that
does not correspond to what that operator does for built-in types. D doesn't
even use + for string concatenation, because Walter thought that that was
operator abuse. Allowing arbitrary code to add overloaded operators to an
existing type is not at all in line with that philosophy.

Regardless, there really isn't much point in arguing this. If you want
things to change, you're going to need to convince Walter, which I very much
doubt is going to happen.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list