Elegant operator overloading in D

前端 未结 2 1295
醉酒成梦
醉酒成梦 2021-02-05 07:39

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

相关标签:
2条回答
  • 2021-02-05 08:34

    Almost all overloaded operators in D are templates by definition. Notice that void opOpAssign(string op)(Vector vector) has a template parameter which is a string. So, no you can't overload it as a non-template function. Now, you don't need a second template to do it (so if by asking whether you need a template, you mean a helper template, then the answer is no), but the overloaded operator function is already a template.

    The canonical way to do what you you're trying to do here is to use string mixins:

    void opOpAssign(string op)(Vector vector)
    {
        mixin("X" ~ op ~ "=vector.X;");
        mixin("Y" ~ op ~ "=vector.Y;");
    }
    
    0 讨论(0)
  • 2021-02-05 08:38

    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 opBinarys restrict what can be passed to opOpAssign but you can go both ways (define opBinary in terms of opOpAssign)

    0 讨论(0)
提交回复
热议问题