abs and minimum values

Dom DiSc dominikus at scherkl.de
Fri Oct 29 08:05:35 UTC 2021


On Thursday, 28 October 2021 at 21:26:04 UTC, kyle wrote:

> Okay I checked the phobos docs and it does say "Limitations
> Does not work correctly for signed intergal types and value 
> Num.min." Should have looked there first, I know. Still seems 
> pretty silly.

I recommend to implement your own abs function this way (was not 
accepted for phobos, as it now does NOT return the same type as 
the argument, which was considered a "breaking change" :-( ):
```D
/// get the absolute value of x as unsigned type. always 
succeeds, even for T.min
Unsigned!T abs(T)(const(T) x) if(isIntegral!T)
{
    static if(isSigned!T) if(x < 0) return cast(Unsigned!T)-x;
    return x;
}
```


More information about the Digitalmars-d-learn mailing list