Another interesting hack: expand a static array into parameter arguments

Simen Kjærås simen.kjaras at gmail.com
Wed Apr 2 14:52:00 PDT 2014


On 2014-04-02 20:54, Andrej Mitrovic wrote:
> On 4/2/14, Andrej Mitrovic <andrej.mitrovich at gmail.com> wrote:
>> On 4/2/14, Timon Gehr <timon.gehr at gmx.ch> wrote:
>>> I guess this would be more useful as a ref-returning @property function?
>>
>> Good point.
>
> It can even be done inside the template:
>
> -----
> template expand(alias array, size_t idx = 0)
>      if (isStaticArray!(typeof(array)))
> {
>      static @property ref Delay(alias arg, size_t idx)() { return arg[idx]; }
>
>      alias Array = typeof(array);
>
>      static if (idx + 1 < Array.length)
>          alias expand = TypeTuple!(Delay!(array, idx),
>                                    expand!(array, idx + 1));
>      else
>          alias expand = Delay!(array, idx);
> }
> -----

In fact, it does not even need to have arg and idx explicitly passed, 
and the alias for Array is redundant:

template expand(alias array, size_t idx = 0)
     if (isStaticArray!(typeof(array)))
{
     @property ref Delay() {
         return array[idx];
     }
     static if (idx + 1 < array.length) {
         alias expand = TypeTuple!(Delay, expand!(array, idx + 1));
     } else {
         alias expand = Delay;
     }
}

--
   Simen


More information about the Digitalmars-d mailing list