Foreach with byte problems

Steven Schveighoffer schveiguy at yahoo.com
Fri Feb 25 11:39:00 PST 2011


On Fri, 25 Feb 2011 14:15:52 -0500, Andrej Mitrovic  
<andrej.mitrovich at gmail.com> wrote:

> Maybe it's best to let D do type infering for me. This works ok:
>
>     foreach (index; byte.min..byte.max+1)
>     {
>         if((index - byte.min) % 4 == 0)
>             writeln();
>
>         writef("%#.2x, ", index);
>     }
>
> I'm fine with that.
>
> Now, what's wrong with this code:
>
>     auto foo = iota(byte.min, byte.max-1);  // ok
>     // foo = [0, 1, .., 124, 125]
>
>     auto bar = iota(byte.min, byte.max);  // fails
>     // Errors:
>     // D:\DMD\dmd2\windows\bin\..\..\src\phobos\std\range.d(3868):
> Error: cannot implicitly convert expression (cast(int)pastLast - 1) of
> type int to byte
>     // D:\DMD\dmd2\windows\bin\..\..\src\phobos\std\range.d(3873):
> Error: cannot implicitly convert expression (cast(int)pastLast + 1) of
> type int to byte
>     // D:\DMD\dmd2\windows\bin\..\..\src\phobos\std\range.d(3890):
> Error: cannot implicitly convert expression
> (cast(uint)cast(int)this.pastLast - this.step) of type uint to byte

IFTI is interpreting the element type of iota to byte.

You need to either explicitly instantiate iota (don't recommend this) or  
cast one of your args to int.

auto bar = iota(cast(int)byte.min, byte.max);

a dirty trick you could do is add 0, which should promote the arg to int.

-Steve


More information about the Digitalmars-d-learn mailing list