help cast

John Colvin john.loughran.colvin at gmail.com
Mon Mar 19 12:10:16 UTC 2018


On Monday, 19 March 2018 at 11:20:05 UTC, Steven Schveighoffer 
wrote:
> Let me adjust your example a bit, and see if you still agree:
>
> auto bytes = cast(ubyte[])[55_444, 289, 1_000_000, 846, 
> 123_456_789];
>
> writeln(bytes); // [148, 33, 64, 78, 21]
>
> I have used cast(ubyte[]) to get ubytes as well, but I normally 
> would do this for values that actually *could be* ubytes. for 
> values higher than ubytes, I would not have expected implicit 
> truncation. It's especially confusing to someone who has seen 
> when you cast an int[] to a ubyte[], and gets the bytes for 
> that same data. When I use cast(ubyte[]), I took it to mean 
> "pretend this is a ubyte[] literal", not "cast each element to 
> ubyte".
>
> I can also see this biting someone who has a long set of 
> ubytes, and accidentally does one that is larger than 255.
>
> -Steve

Raw `cast` is just nasty. It's overloaded and confusing. Wrapper 
template functions like `reinterpretBitsAs` can help alleviate 
the pain, e.g. `assert([1, 2, 
3].reinterpretBitsAs!(ubyte[]).length == 12);`.

I feel like C++ got it right (or just less wrong) with casts.


More information about the Digitalmars-d mailing list