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

tsbockman thomas.bockman at gmail.com
Sat Apr 18 08:25:59 UTC 2020


On Friday, 17 April 2020 at 21:25:34 UTC, kdevel wrote:
> On Friday, 17 April 2020 at 12:59:20 UTC, Simen Kjærås 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 implemented the 
overload of opCast required to make your code work. It's just a 
missing feature.

>> 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 warning is caused by some (very annoying, but intentional) 
changes made to the compiler after std.experimental.checkedint 
was written. That module needs to be updated accordingly, but no 
one has done it yet.

Anyway, you might want to take a look at my checkedint package on 
Dub:

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

In my opinion, the API is better - especially if you use 
SmartInt. (I submitted it for inclusion in the standard library 
originally, but Alexandrescu did not agree with my approach and 
so wrote his own version, which became 
std.experimental.checkedint.)


More information about the Digitalmars-d-learn mailing list