www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - primitive type operator overload

reply "dominic jones" <dominic.jones gmx.co.uk> writes:
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
Apr 20 2012
next sibling parent reply "bearophile" <bearophileHUGS lycos.com> writes:
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
Apr 20 2012
parent Mafi <mafi example.org> writes:
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++).
Apr 20 2012
prev sibling parent "H. S. Teoh" <hsteoh quickfur.ath.cx> writes:
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?"
Apr 20 2012