Operator overloading, structs

Don nospam at nospam.com
Mon Jun 1 21:54:34 PDT 2009


bearophile wrote:
>>> - In #2 D doesn't have a standard method that returns true/false. In Python2.6 such method is named __nonzero__ and in python3 it's named __bool__.<<
> 
> No one has commented about that, but I think that having a way to overload cast(bool)foo is important. I use it in Python and I have shown why and how it can be used in D too. It's an easy thing to do and I think it's safe.

It's definitely required for completeness. In C++ there's a hack to do 
it safely (you return a pointer to a private member class).
Still, I wonder if D could simply do something like defining that for 
classes:
if (x)  is always transformed into  if ( x!=0 )
if (!x) is always transformed into  if ( x==0 )

> 
> Don:
> 
>>> D1 has opCast, but here I think not even a[cast(long)i] works, because BigInt doesn't define it yet. When a big int can't be converted to long, it can throw an exception.
>> Yes, that's not a bad idea.
> 
> But eventually an implicit cast will be better (even if a bit less safe) in D2.

On second thoughts, y = x.toLong or y = to!(long)(x) is probably better. 
Casts are evil, implicit casts even more so.

> 
>> Not toString(), though. You MUST be able to specify if you want leading 
>> zeros, and if you want hex or decimal.
> 
> toString() is for the default case, when you just want the decimal number with no leading zeros. Then you can add other methods to output hex and all you want.
> (In what situations do you want to print leading zeros of a big multiprecision integral value? I have never faced such need so far).

BigFloat, for example.



More information about the Digitalmars-d mailing list