On Monday, 6 August 2018 at 21:23:36 UTC, Paul Backus wrote:
On Monday, 6 August 2018 at 20:22:36 UTC, vit wrote:
On Monday, 6 August 2018 at 19:56:03 UTC, Steven Schveighoffer wrote:

BTW, is there a reason you aren't just using Algebraic?

https://dlang.org/phobos/std_variant.html#.Algebraic

-Steve

primarily visit for Algebraic isn't pure, @nogc, @safe, nothrow.

I wrote the 'sumtype' package to solve this exact problem:

https://code.dlang.org/packages/sumtype

I'm using simpler (and less powerful) version with different visit/visitor syntax:


struct Foo{
        string foo;
}
struct Bar1{
        string bar;
}
struct Bar2{
        string bar;
}

void main()pure nothrow @safe @nogc{
        Variant!(true, Foo, Bar1, Bar2) var; ///Nullable == true
        
        static visit(T)(auto ref const(T) x, string def = ""){
                import std.experimental.all;
                
                static if(is(T == Foo)){
                        return x.foo;
                }
                else static if(false
                        || is(T == Bar1)
                        || is(T == Bar2)
                ){
                        return x.bar;
                }
                else static if(is(T == typeof(null))){
                        return def;
                }
                else static assert(0, "no impl");
        }
        
        assert(var.isa!null);
        assert(var.visitor!visit("null") == "null");
        
        var = Foo("foo");
        assert(var.isa!Foo);
        assert(var.visitor!visit == "foo");
        
        var = Bar1("bar1");
        assert(var.isa!Bar1);
        assert(var.visitor!visit == "bar1");
        
        var = Bar2("bar2");
        assert(var.isa!Bar2);
        assert(var.visitor!visit == "bar2");
        
        var = null;
        assert(var.isa!null);
        
auto var2 = Variant!(false, Foo, Bar1, Bar2)(Foo("foo"));///Nullable == false
        
        assert(var2.visitor!visit == "foo");
        assert(var2.as!Foo.foo == "foo");
        
        ///var2 = null;         //error, variant is not null
        

}

full code: https://dpaste.dzfl.pl/d83ecca23694

Reply via email to