Top 5

Max Samukha samukha at voliacable.com.removethis
Tue Oct 28 05:44:26 PDT 2008


On Tue, 28 Oct 2008 07:12:31 -0400, bearophile
<bearophileHUGS at lycos.com> wrote:

>Max Samukha:
>> Are there still plans for static foreach?
>
>While you/we wait for the static foreach, you can often do something similar defining a Range like this:
>
>template Range(int stop) {
>    static if (stop <= 0)
>        alias Tuple!() Range;
>    else
>        alias Tuple!(Range!(stop-1), stop-1) Range;
>}
>
>In my libs you can find a Range!() for 2 and 3 arguments too (stop, start-stop, start-stop-stride).
>
>Then you can use it for example like this:
>
>auto const foo = [x1, x2, x3];
>foreach (i; Range!(foo.length))
>    func(x1);
>
Nice trick, thanks. I keep overlooking "obvious" things. And even this
works:

void main()
{
    alias Tuple!(1, int, "string") t;

    const l = t.length; // have to use temporary because of a bug
    foreach (i; Range!(l))
    {
        static if (is(t[i]))
            pragma(msg, t[i].stringof ~ " is type");
        else
            pragma(msg, t[i].stringof ~ " is not type");
    }
}

The disadvantage is that you can use the trick only in functions







More information about the Digitalmars-d mailing list