Operators overloading

Timon Gehr timon.gehr at gmx.ch
Sun May 19 03:03:26 PDT 2013


On 05/19/2013 09:32 AM, matovitch wrote:
> Okay, putting the if inside is quite easy :
>

It is not a valid transformation. This removes the condition from the 
signature.

>      const Vertex opBinary(string op)(const ref Vertex vertex)
>      {
>          static /*[...]*/ if (op == "+" || op == "-")
>          {
>              Vertex result = *this;
>              mixin("result" ~ op ~ "= vertex;");
>              return result;
>          }
>      }
>
> But...I'd like to define cross product :
>
>      const T opBinary(string op)(const ref Vertex vertex)
>      {
>          static if (op == "*")
>          {
>              T result = 0;
>              foreach(i; 0..vertex_size)
>                  result += coordinate[i] * vertex.coordinate[i];
>              return result;
>          }
>      }
>
> The compiler is not so great here and doesn't distinguish the two
> opBinary by their signatures. Why ?

Because the two signatures are identical.

const T opBinary(string op)(const ref Vertex vertex);

Do this:

     const Vertex opBinary(string op)(const ref Vertex vertex)
     if (op == "+" || op == "-"){
         Vertex result = *this;
         mixin("result" ~ op ~ "= vertex;");
         return result;
     }

     const T opBinary(string op)(const ref Vertex vertex)
     if (op == "*"){
         T result = 0;
         foreach(i; 0..vertex_size)
             result += coordinate[i] * vertex.coordinate[i];
         return result;
     }



More information about the Digitalmars-d mailing list