match.hpp 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. //
  2. // match.hpp
  3. // case-matcher
  4. //
  5. // Created by Sam Jaffe on 9/10/16.
  6. //
  7. #pragma once
  8. #include <tuple>
  9. namespace matcher {
  10. struct {} any;
  11. using any_t = decltype(any);
  12. template <typename T>
  13. bool operator==(T const &, any_t) { return true; }
  14. template <typename T>
  15. bool operator==(any_t, T const &) { return true; }
  16. template <typename... Args>
  17. struct matcher {
  18. public:
  19. matcher(Args &&... args) : value(std::forward<Args>(args)...) {}
  20. operator bool( ) const { return true; }
  21. bool unmatched( ) const { return ! satisfied; }
  22. template <typename... NArgs>
  23. bool matches(NArgs &&... args) const {
  24. bool const matched = value == std::make_tuple(std::forward<NArgs>(args)...);
  25. satisfied |= matched;
  26. return matched;
  27. }
  28. private:
  29. std::tuple<Args...> value;
  30. mutable bool satisfied = false;
  31. };
  32. template <typename... Args>
  33. matcher<Args...> make_matcher(Args &&... args) {
  34. return matcher<Args...>(std::forward<Args>(args)...);
  35. }
  36. }
  37. #define match( ... ) \
  38. if ( auto const & _matcher_local = \
  39. ::matcher::make_matcher( __VA_ARGS__ ) )
  40. #define with( ... ) \
  41. if ( _matcher_local.unmatched( ) && \
  42. _matcher_local.matches( __VA_ARGS__ ) )
  43. #define else_with( ... ) \
  44. else if ( _matcher_local.matches( __VA_ARGS__ ) )
  45. #define and_with( ... ) \
  46. if ( _matcher_local.matches( __VA_ARGS__ ) )
  47. #define nomatch( ) \
  48. if ( _matcher_local.unmatched( ) )