Operator overloading, structs
Yigal Chripun
yigal100 at gmail.com
Tue Jun 2 13:07:47 PDT 2009
bearophile wrote:
>
> So with your current changes to BigInt, in the following program to
replace the int "i" with a BigInt:
>
> void main() {
> int i = 1;
> if (i)
> i++;
> auto a = [10, 20, 30, 40];
> printf("%d\n", a[i]);
> }
>
> you need to change the code like this:
>
> void main() {
> BigInt i = 1;
> if (i != 0)
> i++;
> auto a = [10, 20, 30, 40];
> printf("%d\n", to!(long)a[i]);
> }
>
> The toBool will help avoid the change in the second line.
>
> I'd like to change programs as little as possible when I change the
> type of a variable from int to BigInt. This has also the big
> advantage that I can write templated algorithms that work with both
> ints and BigInts with as few "static if" as possible (to manage
> BigInts in a special way, for example adding that to!(long) ). That's
> why in such situation an implicit casting is handy.
>
why not just use (i != 0) in both cases? this should work with any
numeric type (so it'll be used in generic code).
conversion of ints to bools in C is IMO a hole in the type system due to
the lack of a boolean type in C. All those narrowing implicit casts
inherited from C are a bad idea IMO.
the need to convert the bigInt to long in order to print it is a design
error in printf() - the format string should specify the formatting of
the variables not their types.
More information about the Digitalmars-d
mailing list