Skip to content

Instantly share code, notes, and snippets.

@YaLTeR
Created September 20, 2017 21:23
Show Gist options
  • Save YaLTeR/830960aba6977807484f7c63b0403d16 to your computer and use it in GitHub Desktop.
Save YaLTeR/830960aba6977807484f7c63b0403d16 to your computer and use it in GitHub Desktop.
Match expressions for std::visit using simple macros.
#include <iostream>
#include <string>
#include <variant>
using namespace std;
#define MATCH(x) \
using __X_TYPE = std::decay_t<decltype(x)>; \
if constexpr (false)
#define CASE(T) \
} else if constexpr (std::is_same_v<__X_TYPE, T>) {
#define DEFAULT \
} else {
int main() {
variant<int, string, double> i = 5, s = string("hello"), d = 23.4;
auto func = [](auto&& x) {
MATCH(x) {
CASE(int) {
cout << "It's an int = " << x << "!\n";
}
CASE(string) {
cout << "It's a string = " << x << "!\n";
}
DEFAULT {
cout << "It's a double = " << x << "!\n";
}
}
};
visit(func, i);
visit(func, s);
visit(func, d);
return 0;
}
@Warepire
Copy link

I am not so sure that I find these constexpr-if statements so horrible that we should poison the code with macros that don't really add anything of value.

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