Checked!({short, ushort, byte, ubyte}, Throw): compilation fails

Simen Kjærås simen.kjaras at gmail.com
Fri Apr 17 12:59:20 UTC 2020


On Friday, 17 April 2020 at 08:59:19 UTC, kdevel wrote:
> On Friday, 17 April 2020 at 04:29:06 UTC, Meta wrote:
>> Unlike C/C++, char is not a numeric type in D; It's a UTF-8 
>> code point:
>
> Thanks, it's a code /unit/. main reads now:
>
> void main ()
> {
>    bar!ubyte;
>    bar!byte;
>    bar!ushort;
>    bar!short;
>    bar!uint;
>    bar!int;
>    bar!ulong;
>    bar!long;
> }
>
> and dmd complains:


The problem is, short/short gives an int answer:

unittest {
     import std.experimental.checkedint;
     Checked!(short, Throw) a;
     pragma(msg, typeof(a/a));
}

So, in your code you get this situation:

unittest {
     import std.experimental.checkedint;
     Checked!(int, Throw) a;
     Checked!(short, Throw) b = a;
}

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;
}

The above code will throw when casting (before the assignment), 
because 65535 can't fit in a short.

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.

--
   Simen


More information about the Digitalmars-d-learn mailing list