union Kinds { int count; string text; } alias TU = TaggedUnion!Kinds; // default initialized to the first field defined TU tu; assert(tu.kind == TU.Kind.count); assert(tu.isCount); // qequivalent to the line above assert(!tu.isText); assert(tu.value!(TU.Kind.count) == int.init); // set to a specific count tu.setCount(42); assert(tu.isCount); assert(tu.countValue == 42); assert(tu.value!(TU.Kind.count) == 42); assert(tu.value!int == 42); // can also get by type assert(tu.countValue == 42); // assign a new tagged algebraic value tu = TU.count(43); // test equivalence with other tagged unions assert(tu == TU.count(43)); assert(tu != TU.count(42)); assert(tu != TU.text("hello")); // modify by reference tu.countValue++; assert(tu.countValue == 44); // set the second field tu.setText("hello"); assert(!tu.isCount); assert(tu.isText); assert(tu.kind == TU.Kind.text); assert(tu.textValue == "hello"); // unique types can also be directly constructed tu = TU(12); assert(tu.countValue == 12); tu = TU("foo"); assert(tu.textValue == "foo");
Implements a generic tagged union type.
This struct takes a union or struct declaration as an input and builds an algebraic data type from its fields, using an automatically generated Kind enumeration to identify which field of the union is currently used. Multiple fields with the same value are supported.
For each field defined by U a number of convenience members are generated. For a given field "foo", these fields are: