Tuple [] operator

Philippe Sigaud philippe.sigaud at gmail.com
Mon Aug 8 13:50:48 PDT 2011


On Mon, Aug 8, 2011 at 21:55, Steven Schveighoffer <schveiguy at yahoo.com> wrote:

> You still can do it, but you have to do it by still using compile-time
> constants as indexes:
>
> auto x = 1;
> Tuple!(int, short) a;
>
> a[0] = 1;
> switch(x)
> {
> case 0:
>   a[0] = 2;
>   break;
> case 1:
>   a[1] = 2;
>   break;
> default:
>   assert(0, "does not compute!");
> }

Christian, I think Steven even suggested in an article some months ago
that this big switch could be generated at compile time.
Steven, do you have a link somewhere?

I mean, the tuple length is known as C-T. It's easy to loop on it and
build a string of cases. If you wrap it in a function, it becomes a
runtime switcher.

Proof of concept:

import std.typecons;

string generateSwitches(T...)()
{
    string result = "switch(x) {\n";
    foreach(i,Type; T)
    {
        result ~= "case " ~ to!string(i) ~ ":\n"
                ~ "fun(tup[" ~ to!string(i) ~ "]);\n"
                ~ "break;\n";
    }
    return result ~ "default:\n"
                  ~ "assert(0, q{Bad index: } ~ to!string(x));\n}";
}

void actOnTuple(alias fun, T...)(int x, ref Tuple!T tup)
{
    mixin(generateSwitches!(T));
}

void foo(T)(ref T t) { writeln(t); t = T.init;}

void main()
{
    auto tup = tuple(1, 3.14, "abc");
    auto x = 1;
    actOnTuple!foo(x, tup);
    writeln(tup);
}


Philippe


More information about the Digitalmars-d-learn mailing list