How to obtain Variant underlying type?

anonymouse anany at mouse.com
Mon Jul 11 06:59:32 UTC 2022


On Monday, 11 July 2022 at 05:41:40 UTC, jfondren wrote:
>
> Oh, sorry. I didn't defend the code in any way because I 
> assumed that the exceptional design would be seen as obviously 
> bad (and that someone else would dig harder in order to find a 
> better solution).

And you were right. I did search for a better solution and came 
across [1]. Although I was having some issues adapting it for my 
use case, Paul Backus' follow-up clarified the issue. This is 
what my naive brain led to before reading this response.

```d
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;
}
```

Didn't see the bugs that would occur when a scalar or empty array 
was passed because I hadn't tested for them.

>         if (!v.length) break;

Pure gold! Bugs are eliminated, and the code is shorter. Thank 
you.

--anonymouse

[1] 
https://tastyminerals.github.io/tasty-blog/dlang/2020/03/22/multidimensional_arrays_in_d.html


More information about the Digitalmars-d-learn mailing list