Map one tuple to another Tuple of different type
Vlad Levenfeld via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sun Jul 20 18:34:07 PDT 2014
On Monday, 21 July 2014 at 01:29:40 UTC, Daniel Gibson wrote:
> Am 21.07.2014 03:05, schrieb Vlad Levenfeld:
>> Thats real weird that it would reject your "i" variable, given
>> that
>> T.length is known at compile time. I think this is a bug. I
>> can get your
>> code to compile if I change your foreach loop to this:
>>
>> foreach(i, U; T)
>> modTuple[i] = transTupleElem(argTuple[i]); // ok
>
> That works indeeed.
>
> I also tried "foreach(int i, x; argTuple)" which also with the
> same error as "foreach(i ; 0 .. T.length)".
>
> As a workaround I created a TupleIndices template, that would
> return a tuple with 0 .. len and did "foreach(i;
> TupleIndices!(T.length)" but that was kinda messy and reminded
> me of the loops I had to jump through in C++ to do anything
> useful with variadic templates..
>
> I agree that this is a bug, but at least your workaround is
> much nicer, thanks a lot! :-)
>
> Cheers,
> Daniel
>
> (@Vlad: Originally I answered you directly because the
> Thunderbird developers thought it was a clever idea to put an
> "answer" button that answers to the author instead of to the
> newsgroup prominently into the GUI)
You're very welcome. The reason foreach(int i, x; argTuple)
failed is because argTuple is a value (of type T), and so known
only at run-time. To get a foreach to run at compile-time, you
have to give it something whose value is known to the compiler
(so, T and typeof(argTuple) would suffice, and 0..T.length really
should as well).
A nice way to test is "pragma(msg, Foo)" where Foo is your
argument... if its knowable at compile-time, then your compiler
should output "Foo" (or the name of whatever its aliasing) to the
console.
More information about the Digitalmars-d-learn
mailing list