Will uniform function call syntax apply to operator overloads?

Steven Schveighoffer schveiguy at yahoo.com
Wed Oct 13 12:24:14 PDT 2010


On Tue, 12 Oct 2010 17:08:16 -0400, Peter Alexander  
<peter.alexander.au at gmail.com> wrote:

> In short, when UFC is working on all types, will this be possible:
>
> Foo opBinary(string op)(Foo a, Foo b)
> {
>      return ...;
> }
>
> Foo x, y;
> Foo z = x + y;
>
> My reasoning here is that x + y is supposedly sugar for  
> x.opBinary!("+")(y), so the free opBinary defined above could be chosen  
> as a pseudo member of Foo.
>
> Will this be possible?

IMO it has to be.  operators use a technique called lowering which  
modifies the original to be as if you typed in the resulting syntax.   
opBinary has no special qualities except that it is the target of the  
lowering, so it should be interpreted like any other template function.

To answer others' questions of why you'd want to do something like this, a  
non-member function has control over the signature of both operands.   
Without an external function, at least one of the operands must be a valid  
reference.

Note the new implementation of comparing two objects for equality, which  
calls opEquals(o1, o2) instead of o1.opEquals(o2).  This significantly  
improves robustness of opEquals since comparing a null object to another  
will not result in a segfault.

Despite all this, I feel we may want to reinvestigate how to prevent  
operators from being hijacked.  An operator is usually implemented with  
intimate knowledge of the two types.  This usually means being implemented  
in the same module at least, if not as a member of the class/struct.  I  
wonder if the lowering could be modified to require that.

-Steve


More information about the Digitalmars-d mailing list