Operator overloading, structs

bearophile bearophileHUGS at lycos.com
Tue Jun 9 05:19:31 PDT 2009


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.


> Alternatively, introduce a "bool opNull()" member function for structs.

A similar method (we can discuss its name, that must be related to its semantic(*)) requires no invisible magic, it's clean and easy to use and implement, and it works on all three cases we have shown. This is a better solution.


(*) I have suggested a name like bool opBool(), so if you perform a cast(bool)x this is the method that is called. But someone has said that in the case of if(x) that's not the method that is implicitly called... But it may be better to call it instead. So for me it's better to leave this to someone more expert than me.

Bye,
bearophile



More information about the Digitalmars-d mailing list