[Issue 1878] foreach does not handle integral types appropriately

d-bugmail at puremagic.com d-bugmail at puremagic.com
Sun Oct 28 16:06:41 PDT 2012


http://d.puremagic.com/issues/show_bug.cgi?id=1878


Andrej Mitrovic <andrej.mitrovich at gmail.com> changed:

           What    |Removed                     |Added
----------------------------------------------------------------------------
                 CC|                            |andrej.mitrovich at gmail.com


--- Comment #1 from Andrej Mitrovic <andrej.mitrovich at gmail.com> 2012-10-28 16:06:36 PDT ---
I think a language change might end up breaking code which assumes the index
variable is always size_t.

The simplest workaround is to type the index variable:
    foreach (ubyte e; 0 .. limit)
        writeln(e);

Otherwise if we want type inference we could implement a library function:

import std.stdio;

struct Walk(T)
{
    T idx;
    T max;

    @property T front() { return idx; }
    @property void popFront() { ++idx; }
    @property bool empty() { return !(idx < max); }
}

auto walk(L, U)(L lwr, U upr)
{
    assert(lwr <= U.max);
    return Walk!U(cast(U)lwr, upr);
}

void main()
{
    ubyte limit = 10;
    ubyte x;

    foreach (e; walk(0, limit))
    {
        writefln("%s %s", typeid(e), e);  // type is ubyte
    }
}

-- 
Configure issuemail: http://d.puremagic.com/issues/userprefs.cgi?tab=email
------- You are receiving this mail because: -------


More information about the Digitalmars-d-bugs mailing list