Initializing static array with contents of (static and dynamic) arrays

Johannes Loher via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Jul 5 08:12:36 PDT 2016


Am 05.07.2016 um 16:39 schrieb Rene Zwanenburg:
> On Tuesday, 5 July 2016 at 12:34:20 UTC, Johannes Loher wrote:
>> I tried this, but it does not work correctly with slices.
> 
> The length of a slice is a runtime value, which is why it can't be used
> to set static array size. What were you trying to achieve? Avoid copying
> the input arrays, or accepting any slice?
> 
> In case of the first, you can put ref in front of the Args:
> auto combineArrays(Args...)(ref Args args)
> 
> The second case will be a bit harder to solve nicely..

I would like to be able, to accept any slice. In the example in my first
post, I need this for key[0..16] and key[16..$] (which are slices).
Strangely enough, the solution I am leaning towards at the moment also
uses length, but it does work for slices of static arrays (i.e. key[0..16]):

template expand(alias A)
{
    auto ref M(alias I)() @property { return A[I]; }
    mixin(q{alias expand = TypeTuple!(}
        ~ iota(A.length).map!(a => "M!" ~ a.to!string).join(",")
        ~ q{);});
}

ubyte[64] buf = [expand!sigma0,
                 expand!key[0..16],
                 expand!sigma1,
                 expand!n,
                 expand!sigma2,
                 expand!key[16..$],
                 expand!sigma3];

I suppose this is because the length of those slices is actually known
at copiletime, but it looks a bit strange to me...

I was trying to write another template that takes several arrays and
expands all of them:

template expand(Args...)
{
    mixin(q{alias expand = TypeTuple!(}
        ~ iota(Args.length).map!(a => "expand!(Args[" ~ a.to!string ~
"])").join(",")
        ~ q{);});
}

It works for static arrays, but not for slices, because the template
parameters are not alias parameters, so the length is then not "known"
at compile time (at least that's what I think why it fails). Is there a
way to specify variadic templates taking any number of alias template
parameters?



More information about the Digitalmars-d-learn mailing list