Operator overloading, structs

bearophile bearophileHUGS at lycos.com
Thu May 28 15:16:08 PDT 2009


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.
- 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.

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).

I think BigInt also may enjoy a lot methods like: int opEquals(int y), etc.

The following code works, but I can't use code like this:


import tango.stdc.stdio: printf;
import tango.math.BigInt: bint = BigInt;
import tango.io.Console: Cout;
import Integer = tango.text.convert.Integer;

void main() {
    bint i = bint(1);
    if (i != bint(0))
        i++;
    auto si = i.toDecimalString();
    Cout(si).newline;
    auto a = [10, 20, 30, 40];
    printf("%d\n", a[Integer.parse(si)]);
}

(Maybe there are ways to improve that code a bit already.)

Bye,
bearophile



More information about the Digitalmars-d mailing list