For a while I was confused about the direction of D\'s operator overloading, but now I realize it\'s a beautiful system... if It would only work with core types (int, float, etc
this is meant to be combined with mixins
void opOpAssign(string op)(Vector vector) {
mixin("X"~op~"=vector.X;");
mixin("Y"~op~"=vector.Y;");
}
not to mention this can easily be coupled to other arithmetic operations
Vector opBinary(string op)(Vector l)if(op=="+"||op=="-"){//only addition and subtraction makes sense for 2D vectors
mixin("return Vector(x"~op~"l.x,y"~op~"l.y;");
}
///take in anything as long as a corresponding binaryOp exists
///this essentially rewrites all "vec op= variable;" to "vec = vec op variable;"
void opOpAssign(string op,T)(T l){
this = this.binaryOp!op(l);
}
and even to other scaling the Vector
Vector opBinary(string op)(real l)if(op=="*"||op=="/"){
mixin("return Vector(x"~op~"l,y"~op~"l;");
}
Vector opBinaryRight(string op)(real l)if(op=="*"){// for 2 * vec
return this*l;
}
note that the defined opBinary
s restrict what can be passed to opOpAssign
but you can go both ways (define opBinary
in terms of opOpAssign
)