Appending static arrays

Stefan Koch via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Jul 18 05:39:01 PDT 2017


On Tuesday, 18 July 2017 at 08:46:50 UTC, Jack Applegame wrote:
> On Monday, 17 July 2017 at 17:38:23 UTC, Nordlöw wrote:
>> I'm want to define a specialization of `append()` that takes 
>> only static arrays as inputs and returns a static array being 
>> the sum of the lengths of the inputs.
>>
>> Have anybody already implemented this?
>>
>> If not, I'm specifically interested in how to most 
>> conveniently infer the length (as an enum) of the returned 
>> static array from the `.length`s of inputs (which of course 
>> must be enum-values too).
>
> My recursive version:
>
> auto concat(T, size_t N, ARRS...)(auto ref T[N] a, auto ref 
> ARRS arrs) {
>     static if(arrs.length == 0) {
>         return a;
>     } else {
>         T[N + arrs[0].length] r = void;
>         r[0..N] = a[];
>         r[N..$] = arrs[0][];
>         return concat(r, arrs[1..$]);
>     }
> }
>
> unittest {
>     int[3] a1 = [1, 2, 3];
>     int[3] a2 = [4, 5, 6];
>     int[3] a3 = [7, 8, 9];
>
>     static assert(is(typeof(concat(a1)) == int[3]));
>     assert(concat(a1) == [1, 2, 3]);
>
>     static assert(is(typeof(concat(a1, a2, a3)) == int[9]));
>     assert(concat(a1, a2, a3) == [1, 2, 3, 4, 5, 6, 7, 8, 9]);
> }

whhhahhh template bloat!!!!!!!!!!!!!!!!!!!!


More information about the Digitalmars-d-learn mailing list