Skip to content

Instantly share code, notes, and snippets.

@redblobgames
Created April 30, 2016 17:20
Show Gist options
  • Save redblobgames/cb26e827977a55d94fc9c9c9b990f3c3 to your computer and use it in GitHub Desktop.
Save redblobgames/cb26e827977a55d94fc9c9c9b990f3c3 to your computer and use it in GitHub Desktop.
mapbox::variant pattern matching
#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...);
}
@redblobgames
Copy link
Author

Note that this is pretty much obsolete now that mapbox has a match() function.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment