indexing tuples using strings

Bill Baxter wbaxter at gmail.com
Mon Dec 1 17:17:41 PST 2008


On Tue, Dec 2, 2008 at 10:14 AM, BCS <ao at pathlink.com> wrote:
> Reply to Bill,
>
>> Isn't there an easier way to fake it using structs? Like
>> template Tuple(T...) { alias T Tuple }
>> struct STuple(T...) { alias T tuple; }
>> alias Tuple!(STuple(int,float), STuple(string,double), int, creal)
>> CantFlattenThis;
>>
>> And you can write flatteners and nesters for that. Seems like fun,
>> maybe I'll waste a few minutes working on that. :-)
>>
>> --bb
>>
>
> Yes, that works well. I make lots of use of that in dparse. I end up with a
> struct type that contains the whole AST defining the grammar to be parsed.
> OTOH there is issues (bugs) with aliases when you try to access it under
> some conditions.
>
>
>

I thought I'd seen it somewhere before.  But I couldn't resist a
little early morning tuple coding challenge.  So here it is.

template Tuple(T...) { alias T Tuple; }
struct STuple(T...) { alias T tuple; }

/** This helper is necessary because the check is(T[0].tuple)
    gives a compiler error
*/
template Flatten1(T) {
    static if (is(T.tuple)) {
        alias T.tuple Flatten1;
    }
    else {
        alias T Flatten1;
    }
}

/// Remove STuples from the tuple T
template Flatten(T...) {
    static if (T.length == 0) {
        alias T Flatten;
    }
    else static if (T.length == 1) {
        alias Flatten1!(T[0]) Flatten;
    }
    else {
        alias Tuple!(Flatten!(T[0]),Flatten!(T[1..$])) Flatten;
    }
}

/// Nest each element of T in a STuple
template Nest(T...) {
    static if (T.length == 0) {
        alias T Nest;
    }
    else static if (T.length == 1) {
        alias STuple!(T) Nest;
    }
    else {
        alias Tuple!(STuple!(T[0]), Nest!(T[1..$])) Nest;
    }
}

void main()
{
    alias Tuple!(STuple!(int,float), STuple!(string,double), int, creal) X;
    pragma(msg,X.stringof);

    alias Flatten!(X) FlatX;
    pragma(msg,FlatX.stringof);

    alias Nest!(FlatX) NestFlatX;
    pragma(msg, NestFlatX.stringof);
}

And the output:
"""
(STuple!(int,float), STuple!(char[],double), int, creal)
(int, float, char[], double, int, creal)
(STuple!(int), STuple!(float), STuple!(char[]), STuple!(double),
STuple!(int), STuple!(creal))
"""



More information about the Digitalmars-d mailing list