View mode: basic / threaded / horizontal-split · Log in · Help
April 20, 2012
primitive type operator overload
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
Re: primitive type operator overload
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
Re: primitive type operator overload
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
Re: primitive type operator overload
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?"
Top | Discussion index | About this forum | D home