Created
April 30, 2016 17:20
-
-
Save redblobgames/cb26e827977a55d94fc9c9c9b990f3c3 to your computer and use it in GitHub Desktop.
mapbox::variant pattern matching
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "variant/variant.hpp" | |
template<typename ...T> using variant = mapbox::util::variant<T...>; | |
namespace matchdetail { | |
template<typename C, typename Arg> | |
Arg lambda_argument(void(C::*)(const Arg&) const) {} | |
template<typename Other> | |
void lambda_argument(Other) {} | |
template<typename Var, typename Fn> | |
void run_if_match(const Var& var, const Fn& code) { | |
typedef decltype(lambda_argument(&Fn::operator())) T; | |
static_assert(!std::is_void<T>::value, "match() lambda must take const T&"); | |
if (var.template is<T>()) { | |
T m = var.template get<T>(); | |
code(m); | |
} | |
} | |
} | |
/* Usage: | |
variant<A, B, C> obj; | |
match(obj, | |
[&](const A& a) { | |
... | |
}, | |
[&](const C& c) { | |
... | |
} | |
); | |
*/ | |
template<typename Var> | |
void match(const Var&) {} | |
template<typename Var, typename First, typename ...Rest> | |
void match(const Var& var, First first, Rest... rest) { | |
matchdetail::run_if_match(var, first); | |
match(var, rest...); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note that this is pretty much obsolete now that mapbox has a
match()
function.