www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - operator overloading rewrite rules

reply "Daniel Kozak" <kozzi11 gmail.com> writes:
On this page http://dlang.org/operatoroverloading.html#Binary, is 
this statement:

"The expression:

a op b
is rewritten as both:

a.opBinary!("$(METACODE op)")(b)
b.opBinaryRight!("$(METACODE op)")(a)"

Which is true when a or b is object or struct, but it doesn't 
work for basic type or arrays wih ufcs.

I mean this:

import std.stdio;

struct S
{
     bool opBinaryRight(string op, T)(T element)
     if (op == "in")
     {
         return true;
     }
}

bool opBinary(string op, T)(T element, T[] array)
if (op == "in")
{
     return true;
}

void main(string[] args)
{
     S s;
     int a;
     int[] b;
     writeln(a.opBinary!"in"(b)); // ok
     writeln(s.opBinaryRight!"in"(a)); // ok
     writeln(a in s); // ok
     writeln(a in b); // doesn't compile
}
Jan 15 2014
parent reply Timon Gehr <timon.gehr gmx.ch> writes:
On 01/15/2014 07:36 PM, Daniel Kozak wrote:
 On this page http://dlang.org/operatoroverloading.html#Binary, is this
 statement:

 "The expression:

 a op b
 is rewritten as both:

 a.opBinary!("$(METACODE op)")(b)
 b.opBinaryRight!("$(METACODE op)")(a)"

 Which is true when a or b is object or struct, but it doesn't work for
 basic type or arrays wih ufcs.
It is this bug: https://d.puremagic.com/issues/show_bug.cgi?id=8062 The problem is that the spec is not explicit about this: "Operator overloading is accomplished by rewriting operators whose operands are class or struct objects into calls to specially named _member functions_." http://dlang.org/operatoroverloading.html Some consider it expected behaviour, based on the explicit mention of 'member function' in the spec.
Jan 15 2014
parent Timon Gehr <timon.gehr gmx.ch> writes:
On 01/15/2014 08:31 PM, Timon Gehr wrote:
 it doesn't work for
 basic type or arrays wih ufcs.
It is this bug: https://d.puremagic.com/issues/show_bug.cgi?id=8062
Also, this enhancement: https://d.puremagic.com/issues/show_bug.cgi?id=9786
Jan 15 2014