Operators overloading in D2

Steven Schveighoffer schveiguy at yahoo.com
Sat Apr 24 06:51:32 PDT 2010


On Sat, 24 Apr 2010 05:07:41 -0400, Dan <daniele.niero at gmail.com> wrote:

> So there's my questions
> Why D2 changed in this way the operators overloading?

To avoid repeating tons of boilerplate code.

For example, you can do this:

void opOpAssign(string op)(ref Vector3 other) if (op == "+=" || op == "-=")
{
    mixin("x " ~ op ~ " other.x");
    mixin("y " ~ op ~ " other.y");
    mixin("z " ~ op ~ " other.z");
}

This takes care of 2 functions with one implementation.  Other types might  
enjoy even more operator coverage, but vectors can't be generalized for  
all operators to one function.

> I saw the the compiler compiles both the functions, even considering  
> this I assume it's not safe to use the old D1 way,
> right?

operator overloads are not special functions, they are just normal  
functions that the compiler calls.  You can still build opAddAssign  
because there is nothing inherently special about that function.   
opAddAssign is a valid symbol name.

> Oh, and I've found the documentation really confusing on this metter.

Hopefully the book will clear this up.

-Steve


More information about the Digitalmars-d-learn mailing list