Skip to content

Instantly share code, notes, and snippets.

@Eczbek
Created February 28, 2025 00:49
Show Gist options
  • Select an option

  • Save Eczbek/ea6d60f335d81a6f12711f264dfc71e9 to your computer and use it in GitHub Desktop.

Select an option

Save Eczbek/ea6d60f335d81a6f12711f264dfc71e9 to your computer and use it in GitHub Desktop.
template<typename... Fs>
struct visitor : Fs... {
using Fs::operator()...;
};
template<auto x>
using value = std::integral_constant<decltype(x), x>;
#define FWD(...) static_cast<decltype(__VA_ARGS__)&&>(__VA_ARGS__)
template<typename T, std::invocable<T> F>
constexpr decltype(auto) operator|(T&& arg, F&& fn) {
return std::invoke(FWD(fn), FWD(arg));
}
#define CXPR_SWITCH(...) value<__VA_ARGS__>() | visitor
#define CXPR_CASE(...) [](value<__VA_ARGS__>) static -> decltype(auto)
#define CXPR_DEFAULT [](...) static -> decltype(auto)
enum Enum {
A,
B
};
template<Enum val>
void do_something() {
std::println("foo");
CXPR_SWITCH (val) {
CXPR_CASE (Enum::A) { std::println("bar"); },
CXPR_CASE (Enum::B) { std::println("baz"); },
CXPR_DEFAULT { std::println("qux"); }
};
}
int main() {
do_something<Enum::A>();
}
@Eczbek
Copy link
Author

Eczbek commented Feb 28, 2025

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