Operators overloading
matovitch
camille.brugel at laposte.net
Sun May 19 03:06:01 PDT 2013
On Sunday, 19 May 2013 at 10:03:27 UTC, Timon Gehr wrote:
> 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;
> }
Oh yes ! You are right...it takes a vertex in both cases. Thanks
for losing your time with me. :-)
More information about the Digitalmars-d
mailing list