Make a type tuple from an array

via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Apr 10 10:53:30 PDT 2015


On Friday, 10 April 2015 at 15:36:42 UTC, John Colvin wrote:
> On Friday, 10 April 2015 at 15:13:54 UTC, Marc Schütz wrote:
>> Is there a way to turn an array (known at compile time) into a 
>> TypeTuple? I want to do a static foreach over it, like this:
>>
>>    foreach(field; fields) {
>>        static if(is(mixin("T." ~ field.name))) { ... }
>>    }
>>
>> Obviously that won't work, because we don't have a real static 
>> foreach yet.
>>
>> I already worked around it with a string mixin, but I'd like 
>> to know whether there's a cleaner way...
>
> For input ranges in general:
>
> import std.range : isInputRange;
>
> template TypeTupleOf(TL...)
>     if (TL.length == 1 && isInputRange!(typeof(TL[0])))
> {
>     import std.typetuple : TT = TypeTuple;
>     enum r = TL[0];
>     static if (r.empty)
>         alias TypeTupleOf = TT!();
>     else
>     {
>         enum f = r.front;
>         alias TypeTupleOf = TT!(
>             f,
>             TypeTupleOf!(
>                 { auto tmp = r; tmp.popFront(); return tmp; }()
>                 )
>             );
>     }
> }
>
> unittest
> {
>     import std.range : iota;
>     foreach(i; TypeTupleOf!(iota(10)))
>     {
>         pragma(msg, i);
>     }
> }

Wow, thanks! I had to `import std.array : empty, front, 
popFront;`, but otherwise it works great.

This should be in Phobos!


More information about the Digitalmars-d-learn mailing list