.tupleof for static array

Paul Backus snarwin at gmail.com
Tue Aug 10 13:10:23 UTC 2021


On Tuesday, 10 August 2021 at 12:01:24 UTC, Dennis wrote:
> ```D
> struct Vec {
>     float x, y, z;
> }
>
> void setPosition(float x, float y, float z) {
>
> }
>
> void main() {
>     Vec posS = Vec(10, 20, 30);
>     setPosition(posS.tupleof); // pass
>
>     float[3] posA = [10, 20, 30];
>     setPosition(posA.tupleof); // Error: no property `tupleof` 
> for type `float[3]`
> }
> ```
>
> Does anyone know a library utility to make expanding a static 
> array like this work?

```d
import std.traits: isStaticArray;

template Iota(size_t n)
{
     import std.meta: AliasSeq;

     static if (n == 0)
         alias Iota = AliasSeq!();
     else
         alias Iota = AliasSeq!(Iota!(n - 1), n - 1);
}

template tupleOf(alias array)
     if (isStaticArray!(typeof(array)))
{
     import std.meta: Map = staticMap;

     ref element(size_t i)()
     {
         return array[i];
     }

     alias tupleOf = Map!(element, Iota!(array.length));
}
```

Full example: https://run.dlang.io/is/COG7m4

Would definitely be nice to have this in the language, though.


More information about the Digitalmars-d-learn mailing list