Advertisement
kevkul

pattern matching

Oct 4th, 2019
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.58 KB | None | 0 0
  1. #include <string>
  2. #include <variant>
  3.  
  4. // Functor composed of a variable number of other functors
  5. // Each inherited functor represents a different type pattern
  6. template<typename ...Types>
  7. struct match : Types... {
  8.     match(Types... types) : Types{ types }... {}
  9.     using Types::operator()...;
  10. };
  11.  
  12. // Type deduction hint
  13. template<typename ...Types>
  14. match(Types...)->match<Types...>;
  15.  
  16. void foo() {
  17.     // Variable whose type is one of { int, std::string }
  18.     auto v = std::variant<int, std::string>{ 5 };
  19.     std::visit(match(
  20.             [](int a) {},
  21.             [](const std::string &b) {}
  22.     ), v);
  23. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement