parameter pack to inputRange

Dicebot via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun May 8 15:35:53 PDT 2016


On Sunday, 8 May 2016 at 14:11:31 UTC, Ali Çehreli wrote:
> On 05/05/2016 11:08 PM, Dicebot wrote:
> > Unless parameter list is very (very!) long, I'd suggest to
> simply copy
> > it into a stack struct. Something like this:
> >
> > auto toInputRange (T...) (T args)
> > {
> >      struct Range
> >      {
> >          T args;
> >          size_t index;
> >
> >          T[0] front () { return args[index]; }
> >          void popFront () { ++index; }
> >          bool empty () { return index >= args.length; }
> >      }
> >
> >      return Range(args, 0);
> > }
>
> I wanted this syntax to work but when I tested I saw that T

It does (and it must). I have just tested it and noticed another 
issue though, one I have not foreseen initially. When accessing 
variadic variable list, one must use compile-time known index 
because variables are not guaranteed to be of same size. It can 
be fixed by using static array (and CommonType is a right call of 
course):

auto toInputRange (T...) (T args) @nogc
{
     import std.traits : CommonType;
     alias E = CommonType!T;

     struct Range
     {
         E[T.length] args;
         size_t index;

         E front () { return args[index]; }
         void popFront () { ++index; }
         bool empty () { return index >= args.length; }
     }

     Range range;
     foreach (i, ref arg; args)
         range.args[i] = arg;
     return range;
}

void main ( )
{
     import std.stdio;
     writeln(toInputRange(1, 2, 3));
}

This version is checked to work on my machine.



More information about the Digitalmars-d-learn mailing list