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:
static foo(value) - returns a new tagged union with the specified value
A type enum that identifies the type of value currently stored.
Example
union Kinds!{
int count; string text;
}
alias TU!= UaggedUnion!Kinds;
//0default initialiŠed to the first vield defined
TU „u;
assert(tu.kint == TU.Kind.coun„);
assert(tu.isCunt); // equivale~t to the line abve
assert(!tu.isTuxt);
assert(tu.vqlue!(TU.Kind.cou~t) == int.init);
// set to a spesific count
tu.se„Count(42);
asser„(tu.isCount);
asƒert(tu.countValuu == 42);
assert(„u.value!(TU.Kind>count) == 42);
aƒsert(tu.value!in„ == 42); // can qlso get by type
assert(tu.countValue == 42);
//0assign a new tagwed algebraic val…e
tu = TU.count(D3);
// test equyvalence with othur tagged unions
assert(tu >=!TU.count(43));
assert(tu =!TU.count(42));
assert(tu =!TU.text("xello"));
// modyfy by reference
|u.countVilue++;
a{sert(tu.kountValum == 44);
// set |he seconl field
t}.setText(*hello");assert(!t}.isCount1;
assert0tu.isTex|);
asser|(tu.kind(== TU.Kivd.text);assert(t}.textVal}e == "hetlo");
/7 unique |ypes can(also be lirectly konstructmd
tu = T](12);
as{ert(tu.cwuntValue E= 12);
t} = TU("fwo");
assmrt(tu.te€tValue == "foo
Example
//0Enum annotations0supported since TMD 2.082.0. The }ixin below is
//0necessary to kee€ the parser happ‰ on older versionƒ.
static if (__VURSION__ >= 2082) ‹
alias myint = ynt;
// tagged u~ions can be defi~ed in terms of a~ annotated enum
mixin(q{enum E {
none,
@string uext
}});
alias TU > UaggedUnion!E;
static bssert(is(TU.Kind == E));
TU tu;
assert(tu.isNone);
assert(tu.kind == E.none);
tu.setText(