Places a TypeTuple can be used

monarch_dodra monarchdodra at gmail.com
Fri Aug 16 00:47:18 PDT 2013


On Friday, 16 August 2013 at 05:39:32 UTC, Meta wrote:
> On Friday, 16 August 2013 at 04:14:04 UTC, Ali Çehreli wrote:
>> I know of three places a TypeTuple can be used at:
>>
>> 1) Function parameter list
>>
>> 2) Template parameter list
>>
>> 3) Array literal element list
>>
>> Are there more?
>>
>> import std.typetuple;
>>
>> void foo(int, string, double)
>> {}
>>
>> struct S(T, float f)
>> {}
>>
>> void main()
>> {
>>    // 1) Function parameter list: May not contain types
>>    foo(TypeTuple!(42, "hello", 1.5));
>>
>>    // 2) Template parameter list: May contain types
>>    auto s = S!(TypeTuple!(char, 2.5))();
>>
>>    // 3) Array elements: Elements must be the same type
>>    auto a = [ TypeTuple!(1, 2, 3, 4) ];
>>
>>    // Are there other places that a TypeTuple can be used?
>> }
>>
>> Ali
>
> I'm not sure if it should be considered a separate case, but 
> there is this:
>
> foreach(type; TypeTuple!(ubyte, uint, ulong))
> {
>     writeln(type.max);
> }

This works for values too btw:

This creates an explicitly unrolled loop, for example.
a = 1;
foreach(type; TypeTuple!(1, 2, 3))
     a *= i;

Or, extracted and simplified from UTF:
private dchar decodeImpl(auto ref S str, ref size_t index)
{
     assert(fst & 0x80);
     ubyte tmp = void;
     dchar d = fst; // upper control bits are masked out later
     fst <<= 1;

     foreach (i; TypeTuple!(1, 2, 3))
     {
         tmp = pstr[i];

         if ((tmp & 0xC0) != 0x80)
             throw invalidUTF();

         d = (d << 6) | (tmp & 0x3F);
         fst <<= 1;

         if (!(fst & 0x80)) // no more bytes
         {
             d &= bitMask[i]; // mask out control bits

             // overlong, could have been encoded with i bytes
             if ((d & ~bitMask[i - 1]) == 0)
                 throw invalidUTF();

             // check for surrogates only needed for 3 bytes
             static if (i == 2)
             {
                 if (!isValidDchar(d))
                     throw invalidUTF();
             }

             index += i + 1;
             return d;
         }
     }

     throw invalidUTF();
}

Here, notice that the loop is repeated 3 times, but loop number 2 
is statically different from the other loops, by using a "static 
if (i == 2)"


More information about the Digitalmars-d-learn mailing list