Elegant operator overloading in D

前端 未结 2 1292
醉酒成梦
醉酒成梦 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;");
    }
    

提交回复
热议问题