Comparison operator overloading

Márcio Martins via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Dec 7 03:36:38 PST 2015


On Monday, 7 December 2015 at 00:43:50 UTC, Ali Çehreli wrote:
> On 12/06/2015 06:41 AM, Márcio Martins wrote:
>
> > auto m = (a > b) * a + 15;
> > auto c = a.choose(a > b)^^2;
>
> What do those operations do? Are you thinking of a special 
> meaning for '>', perhaps common in numerical computations, 
> which I'm not familiar with?
>
> If I understand correctly, 'a > b' in choose(a > b) is the 
> condition to pick elements from a. If so, it is better to pass 
> a lambda in such cases:
>
>   a.choose!((i, j) => i > j);
>
> However, as I understand it, the whole expression is supposed 
> to generate an array-like result. Is that right? :)
>
> Ali

Yes, each expression involving these arrays will almost always 
also result in another array, sometimes with a different type.

For example, a > b returns an array of bools whose elements are 
the the result of the condition applied to each individual 
element of a and b.

This makes writing numerical code very easy, and with fewer bugs, 
because it's all very succinct and each operation is very simple 
and well defined.

My initial intuition was that opBinary and opBinaryRight would be 
used if suitable and opCmp/opEquals would be the fallback. That 
didn't seem to work, so I quickly realised this is not possible 
in D. I'm wondering if it is an oversight in the language design 
or there are real reasons for this limitation?


More information about the Digitalmars-d-learn mailing list