From 6589bac23a5fa04590c006b6e885b69243b78269 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=B6nke=20Ludwig?= Date: Sat, 23 Feb 2019 16:16:20 +0100 Subject: [PATCH] Add TaggedUnion.hasType!T. --- source/taggedalgebraic/taggedunion.d | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/source/taggedalgebraic/taggedunion.d b/source/taggedalgebraic/taggedunion.d index 40b37ba..a564d6e 100644 --- a/source/taggedalgebraic/taggedunion.d +++ b/source/taggedalgebraic/taggedunion.d @@ -203,7 +203,20 @@ struct TaggedUnion(U) if (is(U == union) || is(U == struct) || is(U == enum)) } else { mixin("static @property TaggedUnion "~name~"() { TaggedUnion tu; tu.set!(Kind."~name~"); return tu; }"); } + } + /** Checks whether the currently stored value has a given type. + */ + @property bool hasType(T)() + const { + static assert(staticIndexOf!(T, FieldTypes) >= 0, "Type "~T.stringof~ " not part of "~FieldTypes.stringof); + + final switch (this.kind) { + static foreach (i, n; fieldNames) { + case __traits(getMember, Kind, n): + return is(FieldTypes[i] == T); + } + } } /** Accesses the contained value by reference. @@ -237,8 +250,9 @@ struct TaggedUnion(U) if (is(U == union) || is(U == struct) || is(U == enum)) See_Also: `set`, `opAssign` */ @property ref inout(T) value(T)() inout - if (staticIndexOf!(T, FieldTypes) >= 0) { + static assert(staticIndexOf!(T, FieldTypes) >= 0, "Type "~T.stringof~ " not part of "~FieldTypes.stringof); + final switch (this.kind) { static foreach (i, n; fieldNames) { case __traits(getMember, Kind, n):