Created
September 20, 2017 21:23
-
-
Save YaLTeR/830960aba6977807484f7c63b0403d16 to your computer and use it in GitHub Desktop.
Match expressions for std::visit using simple macros.
This file contains hidden or 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 <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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.