| 43 | template <typename... Ts> overloaded(Ts...) -> overloaded<Ts...>; |
| 44 | |
| 45 | int main() { |
| 46 | Color c = Color::RED; |
| 47 | |
| 48 | auto lambda = [] (auto value) { |
| 49 | std::cout << DoWork<value>() << std::endl; |
| 50 | }; |
| 51 | |
| 52 | magic_enum::enum_switch(lambda, c); // prints "default" |
| 53 | |
| 54 | c = Color::GREEN; |
| 55 | |
| 56 | magic_enum::enum_switch(lambda, c); // prints "override" |
| 57 | |
| 58 | // with object, explicit enum type |
| 59 | auto switcher1 = overloaded{ |
| 60 | [] (magic_enum::enum_constant<Color::BLUE>) { |
| 61 | std::cout << "Blue" << std::endl; |
| 62 | }, |
| 63 | [] (magic_enum::enum_constant<Color::RED>) { |
| 64 | std::cout << "Red" << std::endl; |
| 65 | } |
| 66 | }; |
| 67 | |
| 68 | magic_enum::enum_switch(switcher1, Color::GREEN); // prints nothing |
| 69 | magic_enum::enum_switch(switcher1, Color::BLUE); // prints "Blue" |
| 70 | magic_enum::enum_switch(switcher1, Color::RED); // prints "Red" |
| 71 | |
| 72 | // explicit result type |
| 73 | auto switcher2 = overloaded{ |
| 74 | [] (magic_enum::enum_constant<Color::GREEN>) { |
| 75 | return "called with green argument"; |
| 76 | }, |
| 77 | [] (Color other) { // default case |
| 78 | auto name = magic_enum::enum_name(other); // not empty |
| 79 | return "default: " + std::string{name}; |
| 80 | } |
| 81 | }; |
| 82 | |
| 83 | std::cout << magic_enum::enum_switch<std::string>(switcher2, Color::GREEN) << std::endl; // prints "called with green argument" |
| 84 | std::cout << magic_enum::enum_switch<std::string>(switcher2, Color::RED) << std::endl; // prints "default: RED" |
| 85 | |
| 86 | auto empty = magic_enum::enum_switch<std::string>(switcher2, static_cast<Color>(-3)); // returns an empty string |
| 87 | assert(empty.empty()); |
| 88 | |
| 89 | // result with default object |
| 90 | std::cout << magic_enum::enum_switch<std::string>(switcher2, static_cast<Color>(-3), "unrecognized") << std::endl; // prints "unrecognized" |
| 91 | |
| 92 | auto switcher3 = overloaded{ |
| 93 | [] (magic_enum::enum_constant<Color::RED>) -> std::optional<std::string> { |
| 94 | return "red result"; |
| 95 | }, |
| 96 | [] (magic_enum::enum_constant<Color::BLUE>) -> std::optional<std::string> { |
| 97 | return std::nullopt; |
| 98 | } |
| 99 | }; |
| 100 | |
| 101 | std::cout << std::boolalpha; |
| 102 | std::cout << magic_enum::enum_switch(switcher3, Color::GREEN, std::make_optional("cica")).value() << std::endl; // prints default: "cica" |
nothing calls this directly
no test coverage detected