Operator overloading through UFCS doesn't work

Timon Gehr timon.gehr at gmx.ch
Sat Oct 13 15:12:01 PDT 2012


On 10/13/2012 10:15 PM, Jonathan M Davis wrote:
> ...
> construct is using syntactic sugar such as UFCS, because _all_ of that
> syntactic sugar must be lowered to code which _isn't_ syntactic sugar anymore.

That is not what lowering means.

> It would be far more expensive to have to continually make passes to lower
> code over and over again until no more lowering was required than it would be
> to just have to lower it once.
> ...

It does not have to be implemented it in an inefficient way. It is
actually simpler for a sane compiler implementation to make UFCS apply
to lowered overloaded operators than to restrict it.

> You're reading way to much into what TDPL is saying. It's simply telling you
> about how the compiler goes about translating code which uses operators such
> as +, >, or = into the functions that you used to overload them. It's _not_
> telling you that it'll do UFCS on overloaded operator functions.

It is telling us that

a+b
is transformed to
a.opBinary!"+"(b)

UFCS applies to a.opBinary!"+"(b).

> Heck,
> technically, TDPL never really says that D _has_ UFCS. It talks about the
> member call function syntax for _arrays_ (which D had for ages before it had
> UFCS), not for types in general. It's only very recently that full UFCS has
> been added to the language.

Exactly, so what is the point? If TDPL does not talk about the UFCS
feature, then TDPL not talking about UFCS in the context of one
specific case certainly cannot be used as an argument to justify that
it should not apply in that case.

> Both overloaded operators and UFCS use lowering to generate different code
> which the compiler then compiles,

By using the same strategy recursively, otherwise it is not called lowering.

> but they _aren't_ mixed and they will
> _never_ be mixed. If it had _ever_ been intended that it be possible to
> overload operators as free functions, then we'd simply have made it so that
> you could declare a free function like
>
> auto opBinary(string op)(Foo foo, Bar bar)
> {
>     ...
> }
>
> in the first place  without requiring that it be a member function.

You can.

> But it _was_
> required to be a member function, and it would make no sense to allow a new
> feature to circumvent that restriction. If it was supposed to be
> circumventable, then the restriction wouldn't have been put there in the first
> place.

This argument is even less convincing in the context of an informally
specified language with a somewhat buggy reference compiler.


More information about the Digitalmars-d-learn mailing list