How to obtain Variant underlying type?

Salih Dincer salihdb at hotmail.com
Mon Jul 11 07:13:57 UTC 2022


On Monday, 11 July 2022 at 06:59:32 UTC, anonymouse wrote:
> I did search for a better solution and came across...
> https://tastyminerals.github.io/tasty-blog/dlang/2020/03/22/multidimensional_arrays_in_d.html

I like it!

It's been a good collaboration...

```d
import std.variant;

auto generate(T)(size_t x, size_t y) {
   T[][] result;
   ubyte[] arr = new ubyte[x * y * T.sizeof];
   size_t m = y * T.sizeof;

   foreach (i; 0 .. x) {
     size_t n = i * m;
     result ~= cast(T[])arr[n .. n + m];
   }
   return result;
}

size_t[] shape(Variant v) {
   typeof(return) dims;

   while (cast(TypeInfo_Array) v.type !is null) {
     dims ~= v.length;
     v = v[0];
   }

   if (!dims.length && v.length) {
     dims ~= v.length;
     dims ~= 0;
   }
   return dims;
}

void main() {
   foreach(x; 1..100) {
     foreach(y; 1..100) {
       auto test = Variant(generate!int(x, y));
       assert(shape(test) == [x, y]);
     }
   }
}
```

SDB at 79


More information about the Digitalmars-d-learn mailing list