Make a type tuple from an array
John Colvin via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Fri Apr 10 11:25:13 PDT 2015
On Friday, 10 April 2015 at 17:53:31 UTC, Marc Schütz wrote:
> 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.
Haha, yeah... I forgot where they were, they aren't documented in
std.array (grrrr), so I just left it for someone else to find :p
> This should be in Phobos!
Yup. I've mentioned it here:
https://github.com/D-Programming-Language/phobos/pull/3128 but
it's a bit of a complicated situation as a bunch of names are
likely to change.
More information about the Digitalmars-d-learn
mailing list