match.hpp 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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. template <typename... Args>
  11. struct matcher {
  12. public:
  13. matcher(Args &&... args) : value(std::forward<Args>(args)...) {}
  14. operator bool( ) const { return true; }
  15. bool unmatched( ) const { return ! satisfied; }
  16. template <typename... NArgs>
  17. bool matches(NArgs &&... args) const {
  18. bool const matched = value == std::make_tuple(std::forward<NArgs>(args)...);
  19. satisfied |= matched;
  20. return matched;
  21. }
  22. private:
  23. std::tuple<Args...> value;
  24. mutable bool satisfied = false;
  25. };
  26. template <typename... Args>
  27. matcher<Args...> make_matcher(Args &&... args) {
  28. return matcher<Args...>(std::forward<Args>(args)...);
  29. }
  30. }
  31. #define match( ... ) \
  32. if ( auto const & _matcher_local = \
  33. ::matcher::make_matcher( __VA_ARGS__ ) )
  34. #define with( ... ) \
  35. if ( _matcher_local.unmatched( ) && \
  36. _matcher_local.matches( __VA_ARGS__ ) )
  37. #define else_with( ... ) \
  38. else if ( _matcher_local.matches( __VA_ARGS__ ) )
  39. #define and_with( ... ) \
  40. if ( _matcher_local.matches( __VA_ARGS__ ) )
  41. #define nomatch( ) \
  42. if ( _matcher_local.unmatched( ) )
  43. #include "matchers/any_in.hpp"
  44. #include "matchers/any_of.hpp"
  45. #include "matchers/any.hpp"
  46. #include "matchers/matches.hpp"