Checked!({short, ushort, byte, ubyte}, Throw): compilation fails
    kdevel 
    kdevel at vogtner.de
       
    Fri Apr 17 21:25:34 UTC 2020
    
    
  
On Friday, 17 April 2020 at 12:59:20 UTC, Simen Kjærås wrote:
[Deleted text makes sense]
> And assigning from an int to a short may discard data, so it's 
> statically disallowed by Checked.
> This is a deliberate design choice, and the appropriate way to 
> handle it is with a cast:
>
> unittest {
>     import std.experimental.checkedint;
>     Checked!(int, Throw) a = 65535;
>     Checked!(short, Throw) b = cast(short)a;
> }
A curiosity. Usually you cast into the type on the left. But
    Checked!(short, Throw) b = cast (Checked!(short, Throw)) a;
does not compile:
    Error: template std.experimental.checkedint.Checked!(int,
    Throw).Checked.opCast cannot deduce function from argument 
types
    !(Checked!(short, Throw))(), candidates are: [...]
One has to go over the underlying type?
> The above code will throw when casting (before the assignment), 
> because 65535 can't fit in a short.
It's remarkable that the cast to the /underlying type/ throws. I 
would have expected that
    cast(short) a
is equivalent to what actually must be written as
    cast(short) a.get
> You also get a deprecation message, about an integral promotion 
> not being performed. I believe the result is correct and the 
> warning can be ignored.
So the warning is a bug?
void foo (T) ()
{
    import std.experimental.checkedint;
    alias CT = Checked!(T, Throw);
    CT c = CT.min;
    CT b;
    --b;
    c /= b;
}
    
    
More information about the Digitalmars-d-learn
mailing list