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

tsbockman thomas.bockman at gmail.com
Sat Apr 18 08:39:52 UTC 2020


On Friday, 17 April 2020 at 21:25:34 UTC, kdevel wrote:
> 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 author of std.experimental.checkedint hasn't (yet) written 
the opCast overload required to make that code work. It's just a 
feature missing from the code for that specific module in the 
standard library, not a language issue.

>> 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?

The deprecation message is a consequence of a (very annoying) 
language change made after std.experimental.checkedint was 
written. It's not really a bug, although someone should probably 
fix it anyway.

Anyway, you might want to give my checkedint package on DUB a 
try, instead:

     https://code.dlang.org/packages/checkedint

(It's the original candidate for std.experimental.checkedint. 
Alexandrescu didn't like it, so he rejected it and wrote his own. 
But, I still think mine has a better API, especially if you use 
the SmartInt types.)


More information about the Digitalmars-d-learn mailing list