Operator overloading, structs

Don nospam at nospam.com
Mon Jun 1 17:02:13 PDT 2009


bearophile wrote:
> This post is mostly about D2 operator overloading in general, but I also talk about problems in the API of Tango BigInts.
> 
> A small program that use multiprecision integers of Tango:
> 
> 
> import tango.stdc.stdio: printf;
> import tango.math.BigInt: bint = BigInt;
> 
> void main() {
>     bint i = 1; // #1
>     if (i) // #2
>         i++;
>     auto a = [10, 20, 30, 40];
>     printf("%d\n", a[i]); // #3
> }
> 
> 
> If you replace BigInt with int that program works.
> With bigInteger it doesn't work, because I think:
> - In #1 it doesn't call static opCall.
Works for me with int. I've fixed BigInt so that it now works with long 
as well.

> - 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__.
> - In #3 there's no implicit cast to int.

> 
> I think that improving such D2 operator overloading is very good, it allows to use BigInts, SafeInts, Complex, etc, in a quite more transparent way, allowing very similar code to work with native and user defined types.
> 
> ---------------
> 
> Regarding specifically BigInt:
> 
> 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.

> Until a more efficient solution is found, I think BigInts must have a toString too. In most situations you don't print such numbers, you do lot of computations with them and then you finally print some of them. So often the time spent printing them is not much).

Not toString(), though. You MUST be able to specify if you want leading 
zeros, and if you want hex or decimal. I just (a) haven't got around to 
it; and (b) haven't been sure about the interface should be.

But I hate toString() so much, I'm _never_ going to support it. It's an 
OMDB (over my dead body). Sorry.

> I think BigInt also may enjoy a lot methods like: int opEquals(int y), etc.
Ouch! That's a simple omission.
Fixed in Tango SVN 4717.



More information about the Digitalmars-d mailing list