Thread overview
Access to intersection fields of an algebraic data type
Jan 19, 2019
sighoya
Jan 19, 2019
Meta
Jan 19, 2019
sighoya
Jan 20, 2019
Nicholas Wilson
January 19, 2019
Is there a solution for the following problem:

import std.variant : Algebraic;

struct A
{
    int a=2;
}

struct B
{
    int a=2;
};

void main()
{
    Algebraic!(A,B) c=A();
    writeln(c.a);
    return;
}

Error: no property a for type VariantN!(4LU, A, B)
January 19, 2019
On Saturday, 19 January 2019 at 17:40:53 UTC, sighoya wrote:
> Is there a solution for the following problem:
>
> import std.variant : Algebraic;
>
> struct A
> {
>     int a=2;
> }
>
> struct B
> {
>     int a=2;
> };
>
> void main()
> {
>     Algebraic!(A,B) c=A();
>     writeln(c.a);
>     return;
> }
>
> Error: no property a for type VariantN!(4LU, A, B)

You want the untyped version of std.variant.visit:

writeln(c.visit!(aOrB => aOrB.a));
January 19, 2019
On Saturday, 19 January 2019 at 17:51:58 UTC, Meta wrote:
> On Saturday, 19 January 2019 at 17:40:53 UTC, sighoya wrote:
>> Is there a solution for the following problem:
>>
>> import std.variant : Algebraic;
>>
>> struct A
>> {
>>     int a=2;
>> }
>>
>> struct B
>> {
>>     int a=2;
>> };
>>
>> void main()
>> {
>>     Algebraic!(A,B) c=A();
>>     writeln(c.a);
>>     return;
>> }
>>
>> Error: no property a for type VariantN!(4LU, A, B)
>
> You want the untyped version of std.variant.visit:
>
> writeln(c.visit!(aOrB => aOrB.a));

Thanks @Meta,

With the help of dlang's UFCS, we can rewrite it more idiomatically as:

import std.variant : Algebraic;

struct A
{
    int a=2;
}

struct B
{
    int a=2;
};

int a(Algebraic!(A,B) c)
{
    return cast(int)(visit!((c)=>c.a)(c));
}

void main()
{
    Algebraic!(A,B) c=A();
    writeln(c.a);
    return;
}

January 20, 2019
On Saturday, 19 January 2019 at 17:40:53 UTC, sighoya wrote:
> Is there a solution for the following problem:
>
> import std.variant : Algebraic;
>
> struct A
> {
>     int a=2;
> }
>
> struct B
> {
>     int a=2;
> };
>
> void main()
> {
>     Algebraic!(A,B) c=A();
>     writeln(c.a);
>     return;
> }
>
> Error: no property a for type VariantN!(4LU, A, B)

Try using http://code.dlang.org/packages/taggedalgebraic I find it much better.