Operator overloading, structs

Don nospam at nospam.com
Tue Jun 9 17:27:00 PDT 2009


bearophile wrote:
> Don:
>> That is, if x is a struct, convert "if(x)" into "if(x==0)"
>> and convert "if(!x)" into "if(x!=0)". Usual rules would then apply, so 
>> any opEquals with a parameter which could be implicitly cast from 0 
>> would work.
>> That wouldn't allow smart-pointer structs to implement if (x) without 
>> requiring them to allow comparisons with integers, so it might be 
>> necessary to add a second step: try "if(x==null)" instead.
> 
> I don't like this solution, because it relies on a bit of invisible magic, and you too have seen it needs extensions because it's not general.
> If you want to use if (x) where x doesn't represent a number but something else like a collection, they you have to add even more special cases like add a third step: "if(x.length == 0)" etc. So this is not a good solution.

Currently, if(x) is a shortcut for either:
if (x != 0)
OR
if (x !is null)

depending on whether x is a value or a reference type. It never means 
anything else. I think it should stay that way.
That is, if it is not legal to check it for equality with 0, the 
shortcut should not exist. And definitely, if "if(x!=0)" is a valid 
operation, it should never be different to "if(x)".
BTW, in C++, it only ever means "x!=0", it's only because D treats null 
differently from 0 that the two cases exist.



More information about the Digitalmars-d mailing list