Algebraic changing type when in associative array

Paul Backus snarwin at gmail.com
Wed Feb 5 07:02:49 UTC 2020


On Wednesday, 5 February 2020 at 01:06:46 UTC, rous wrote:
> This is an example program that illustrates the issue:
>
> import std.variant: Algebraic, This;
> import std.stdio: writeln;
> alias Foo = Algebraic!(This[], int);
> void main()
> {
>     Foo x = 5;
>     Foo y = 10;
>     Foo z = [x,y];
>     pragma(msg, typeof(x));
>     pragma(msg, typeof(y));
>     pragma(msg, typeof(z));
>     pragma(msg, typeof(z[0]));
> }
> At compile time, it prints VariantN!(16LU, This[], int) three 
> times and then VariantN!32LU.

The problem is that you are indexing directly into the Algebraic, 
using VariantN.opIndex [1], which returns a generic, 
non-Algebraic Variant. Instead, you should use visit [2] or 
tryVisit [3] to access the array contained inside the Algebraic, 
and index into that.

For example:

auto w = z.tryVisit!((Foo[] arr) => arr[0]);
static assert(is(typeof(w) == Foo));

[1] https://dlang.org/phobos/std_variant.html#.VariantN.opIndex
[2] https://dlang.org/phobos/std_variant.html#.visit
[3] https://dlang.org/phobos/std_variant.html#.tryVisit


More information about the Digitalmars-d-learn mailing list