Operators overloading

Timon Gehr timon.gehr at gmx.ch
Sun May 19 04:04:13 PDT 2013


On 05/19/2013 12:41 PM, Idan Arye wrote:
> ...
>
> I think a better syntax would be:
>
>      const Vertex opBinary(string op : "+", "-")(const ref Vertex vertex)
>
> this will save a bit of ambiguity(`op` is a `string` specialization of
> `string[]`?)
>

It moves the ambiguity from analysis into the parser.

> At any rate, I'm not sure how useful it would be. Operator overloading
> code usually fit for a single operator - you usually write one for each
> operator:
>
>      const Vertex opBinary(string op : "+")(const ref Vertex vertex)
>      {
>          Vertex result = this;
>          result += vertex;
>          return result;
>      }
>      const Vertex opBinary(string op : "-")(const ref Vertex vertex)
>      {
>          Vertex result = this;
>          result -= vertex;
>          return result;
>      }
>

Your example shows how operator overloading code often fits for multiple 
operators.

> If you want to have several operators in the same method, you can afford
> the verbosity of:
>
>      const Vertex opBinary(string op)(const ref Vertex vertex)
>          if (__traits(compiles, mixin("this " ~ op ~ "= vertex;")))
>      {
>          Vertex result = /*[...]*/this;
>          mixin("result" ~ op ~ "= vertex;");
>          return result;
>      }

This kind of template constraint may allow leaking of implementation 
details.

Eg. v.opBinary!".foo+"


More information about the Digitalmars-d mailing list