From be4a93e553776aba5c98c0da52c69a9b2ac79806 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=B6nke=20Ludwig?= Date: Sun, 28 May 2017 22:28:39 +0200 Subject: [PATCH] Make apply() work for plain values, too. This provides symmetry between TaggedAlgebraic values and ordinary values. --- source/taggedalgebraic.d | 32 +++++++++++++++++--------------- 1 file changed, 17 insertions(+), 15 deletions(-) diff --git a/source/taggedalgebraic.d b/source/taggedalgebraic.d index 5a2771c..d0ae615 100644 --- a/source/taggedalgebraic.d +++ b/source/taggedalgebraic.d @@ -639,6 +639,12 @@ auto apply(alias handler, TA)(TA ta) } } } +/// ditto +auto apply(alias handler, T)(T value) + if (!isInstanceOf!(TaggedAlgebraic, T)) +{ + return handler(value); +} /// unittest { @@ -648,31 +654,27 @@ unittest { } alias TA = TaggedAlgebraic!U; - auto ta = TA(12); - bool matched = false; - ta.apply!((v) { + assert(TA(12).apply!((v) { static if (is(typeof(v) == int)) { assert(v == 12); - assert(!matched); - matched = true; + return 1; } else { - assert(false); + return 0; } - }); - assert(matched); + }) == 1); - ta = TA("foo"); - matched = false; - ta.apply!((v) { + assert(TA("foo").apply!((v) { static if (is(typeof(v) == string)) { assert(v == "foo"); - assert(!matched); - matched = true; + return 2; } else { - assert(false); + return 0; } + }) == 2); + + "baz".apply!((v) { + assert(v == "baz"); }); - assert(matched); }