How to obtain Variant underlying type?

jfondren julian.fondren at gmail.com
Sun Jul 10 06:26:37 UTC 2022


On Saturday, 9 July 2022 at 23:04:20 UTC, anonymouse wrote:
> On Saturday, 9 July 2022 at 14:46:36 UTC, Adam D Ruppe wrote:
>>
>> Impossible; Variant's type is only known at runtime, and this 
>> would require compile time knowledge.
>
> Hmmm. Okay, thanks. What I really need to know is how many 
> dimensions an array has and the total elements per dimension so 
> that I can create temporary storage for it later.
>
>      this(T)(T a)
>      in(imported!"std.traits".isDynamic!T)
>      {
>          data = a; // data is of type Variant
>          shape = [a.length, {?, ...}]; // what's the best way 
> to deterine?
>      }
>
> Thanks,
> --anonymouse

```d
import std.variant : Variant;

size_t[] shape(Variant v) {
     import std.variant : VariantException;

     size_t[] s;
     try {
         while (true) {
             Variant elem = v[0];
             s ~= v.length;
             v = elem;
         }
     } catch (VariantException e) {
         return s;
     }
}

unittest {
     assert([3, 1] == [[1], [2], [3]].Variant.shape);
     assert([2, 1] == [[1], [2]].Variant.shape);
     assert([2, 2] == [[1, 0], [2, 0]].Variant.shape);
     assert([2] == [1, 2].Variant.shape);
     assert([] == 2.Variant.shape);

     // irregularity not checked
     assert([2, 2] == [[1, 0], [2]].Variant.shape);
     // arguably should be [2, 0]
     assert([2] == [[], []].Variant.shape);
}
```


More information about the Digitalmars-d-learn mailing list