Thread overview
primitive type operator overload
Apr 20, 2012
dominic jones
Apr 20, 2012
bearophile
Apr 20, 2012
Mafi
Apr 20, 2012
H. S. Teoh
April 20, 2012
Hello,

I want to overload a primitive type operator so that I can do something like

double a;
myStruct b;
writeln(a + b);

but have no idea how to do it. Something similar(?) is already implemented in the language, i.e.

double x;
double[] y;
writeln(x + y);

but after searching the dmd2/src, what I found didn't offer any help.

-Dominic Jones
April 20, 2012
Dominic Jones:

> I want to overload a primitive type operator so that I can do something like
>
> double a;
> myStruct b;
> writeln(a + b);

You can't overload the operator of a primitive, but binary operators come in left and right versions:
http://dlang.org/operatoroverloading.html#Binary

a.opBinary!("op")(b)
b.opBinaryRight!("op")(a)

so adding an inverse "+" operator inside myStruct is possible.

Bye,
bearophile
April 20, 2012
Am 20.04.2012 18:41, schrieb bearophile:
> Dominic Jones:
>
>> I want to overload a primitive type operator so that I can do
>> something like
>>
>> double a;
>> myStruct b;
>> writeln(a + b);
>
> You can't overload the operator of a primitive, but binary operators
> come in left and right versions:
...
>
> Bye,
> bearophile

Shouldn't a consequence of UFCS be that you can overload binary operators for primitives, as should global overloads (like in C++).
April 20, 2012
On Fri, Apr 20, 2012 at 07:12:41PM +0200, Mafi wrote:
> Am 20.04.2012 18:41, schrieb bearophile:
> >Dominic Jones:
> >
> >>I want to overload a primitive type operator so that I can do something like
> >>
> >>double a;
> >>myStruct b;
> >>writeln(a + b);
> >
> >You can't overload the operator of a primitive, but binary operators come in left and right versions:
> ...
> >
> >Bye,
> >bearophile
> 
> Shouldn't a consequence of UFCS be that you can overload binary operators for primitives, as should global overloads (like in C++).

UFCS only kicks in if no matching method is found for the given type. So UFCS can be used to provide "default" implementations for when an operator is not defined for a given type, but the operator defined by the type takes precedence over UFCS.


T

-- 
"How are you doing?" "Doing what?"