Operator overloading through UFCS doesn't work

Jonathan M Davis jmdavisProg at gmx.com
Sat Oct 13 02:49:45 PDT 2012


On Saturday, October 13, 2012 11:41:07 Tommi wrote:
> On Saturday, 13 October 2012 at 09:06:28 UTC, Jakob Ovrum wrote:
> > Do note that this says *method* call. Your example doesn't use
> > methods. Hence, the current state of operator overloading is
> > consistent with TDPL.
> 
> I don't agree with the last sentence. According to TDPL:
> 
> 1) "whenever at least one participant in an operator expression
> is of user-defined type, the compiler rewrites the expression
> into a regular method call with a specific name"
> ---------------------------------------------------------------
> ++var;
> gets rewritten to:
> var.opUnary!"++"();
> 
> 2) "if a.fun(b, c, d) is seen but fun is not a member of a’s
> type, D rewrites that as fun(a, b, c, d) and tries that as well"
> ----------------------------------------------------------------
> So, because opUnary is not a member of var, compiler should
> rewrite that as:
> .opUnary!"++"(var);

Just because the overloaded operator is rewritten into a method call 
underneath the hood doesn't mean that the UFCS rewrite also applies. The 
transformation of an operator to a method or a UFCS call to a free function is 
done _once_. You don't get both. It is most definitely _by design_ that you 
cannot overload operators except as member functions. If TDPL says otherwise, 
it's either because you're misunderstanding what it's saying or because it's 
wrong.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list