Appending static arrays

ag0aep6g via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Jul 17 12:06:23 PDT 2017


On 07/17/2017 08:35 PM, Nordlöw wrote:
> Thanks, but I'm talking about the variadic case where the number of 
> input arguments are unknown (>= 2) where the function header looks 
> something like
> 
> import std.traits : allSatisfy, isStaticArray;
> 
> auto append(R, Args...)(auto ref Args args)
>      if (args.length >= 2 &&
>          allSatisfy!(isStaticArray, Args))
>      // TODO all ElementTypes have CommonType
> {
>      // ...
> }
> 

I see. Here's what I could come up with:

----
import std.traits : allSatisfy, isStaticArray;

auto append(Args...)(auto ref Args args)
     if (args.length >= 2 &&
         allSatisfy!(isStaticArray, Args))
{
     import std.algorithm : sum;
     import std.meta : staticMap;
     import std.range: ElementType;
     import std.traits : CommonType;

     enum staticArrayLength(A : E[n], E, size_t n) = n;

     alias E = ElementType!(Args[0]);
     static assert(is(CommonType!(staticMap!(ElementType, Args)) : E));
     enum lengths = staticMap!(staticArrayLength, Args);

     E[sum([lengths])] result;
     foreach (i, length; lengths)
     {
         enum offset = sum!(size_t[])([lengths[0 .. i]]);
         result[offset .. offset + length] = args[i];
     }
     return result;
}

@nogc unittest
{
     int[3] a = [1, 2, 3];
     const int[4] b = [4, 5, 6, 7];
     immutable int[5] c = [8, 9, 10, 11, 12];

     auto r = append(a, b, c);
     assert(r == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]);
     static assert(is(typeof(r) == int[12]));
}
----


More information about the Digitalmars-d-learn mailing list