T.zero and T.one for numeric types

Biotronic via Digitalmars-d digitalmars-d at puremagic.com
Fri Apr 17 06:27:18 PDT 2015


I've been writing a lot of generic code lately that has to deal 
with various kinds of numbers, and have near been driven nuts by 
the fact there is no uniform way to get a zero or one.

Consider:

    void foo(T)(T a) {}

    foo!T(0);

Does this work with all built-in numeric types? Yes.
Does it work with T=BigInt or Complex!float? No.

Now, those are a limited set of possibilities, and one could 
easily enough create a template such that

    foo!BigInt(zero!BigInt);

would work. But why can't I instead, for every numeric type, 
simply write

    foo(BigInt.zero);
    foo(float.one);
    foo(Complex!float.zero);
    foo(Rational!BigInt.one);
    foo(Meters.zero);

?

This would also work for strong typedefs and units of 
measurement, where simply assigning 0 to a variable might not 
work (because it lacks the correct unit).

It's a very simple change, both in the compiler and Phobos, and I 
could have a pull request ready tomorrow.

--
   Simen


More information about the Digitalmars-d mailing list