Search code examples
operator-overloadingd

Does D automatically rewrite opBinary to opOpAssign?


for example, assuming that T implements the right operator overloads:

T t1, t2, t3;
t3 = t1 + t2; // t3.opAssign(t1.opBinary!"+"(t2)) for sure
t3 = t3 + t2; // rewritten to t3.opOpAssign!"+"(t2) ?

Is the last operation optimized by D ?


Solution

  • No, it is not. It is not possible, because opBinary and opOpAssign could have different semantic:

    struct S
    {
        int val = 5;
    
        S opBinary(string op)(S rhs) if (op == "+")
        {
            return S(val + rhs.val);
        }
    
        void opOpAssign(string op)(S rhs) if (op == "+")
        {
            val = val - rhs.val;
        }
    }
    
    void main()
    {
        import std.stdio;
    
        S s1, s2, s3;
        writeln(s3); // S(5)
    
        s3 = s3 + s2;
        writeln(s3); // S(10)
    
        s3.val = 5;
        writeln(s3); // S(5)
    
        s3 += s2;
        writeln(s3); // S(0)
    }