Opinions: The Best and Worst of D (for a lecture/talk I intend to give)

Dominikus Dittes Scherkl via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Jul 9 09:24:38 PDT 2014


On Wednesday, 9 July 2014 at 14:51:41 UTC, Meta wrote:
> One of the uglier things in D is also a long-standing problem 
> with C and C++, in that comparison of signed and unsigned 
> values is allowed.

I would like that, if it would be implemented along this line:

/// Returns -1 if a < b, 0 if they are equal or 1 if a > b.
/// this will always yield a correct result, no matter which 
numeric types are compared.
/// It uses one extra comparison operation if and only if
/// one type is signed and the other unsigned but the signed 
value is >= 0
/// (that is what you need to pay for stupid choice of type).
int opCmp(T, U)(const(T) a, const(U) b) @primitive if(isNumeric!T 
&& isNumeric!U)
{
    static if(Unqual!T == Unqual!U)
    {
       // use the standard D implementation
    }
    else static if(isFloatingPoint!T || isFloatingPoint!U)
    {
       alias CommonType!(T, U) C;
       return opCmp!(cast(C)a, cast(C)b);
    }
    else static if(isSigned!T && isUnsigned!U)
    {
       alias CommonType!(Unsigned!T, U) C;
       return (a < 0) ? -1 : opCmp!(cast(C)a, cast(C)b);
    }
    else static if(isUnsigned!T && isSigned!U)
    {
       alias CommonType!(T, Unsigned!U) C;
       return (b < 0) ? 1 : opCmp!(cast(C)a, cast(C)b);
    }
    else // both signed or both unsigned
    {
       alias CommonType!(T, U) C;
       return opCmp!(cast(C)a, cast(C)b);
    }
}


More information about the Digitalmars-d-learn mailing list