match.hpp 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. //
  2. // match.hpp
  3. // case-matcher
  4. //
  5. // Created by Sam Jaffe on 9/10/16.
  6. //
  7. #pragma once
  8. #include <array>
  9. #include <tuple>
  10. namespace matcher {
  11. struct {} any;
  12. using any_t = decltype(any);
  13. template <typename T>
  14. bool operator==(T const &, any_t) { return true; }
  15. }
  16. namespace matcher {
  17. template <typename T, size_t I>
  18. struct any_of_t {
  19. std::array<T, I> options;
  20. };
  21. template <typename T, size_t I>
  22. bool operator==(T const & t, any_of_t<T, I> const & of) {
  23. return std::find(of.options.begin(), of.options.end(), t) != of.options.end();
  24. }
  25. template <typename... Args>
  26. any_of_t<typename std::common_type<Args...>::type, sizeof...(Args)> any_of(Args &&... args) {
  27. return {{args...}};
  28. }
  29. }
  30. namespace matcher {
  31. template <typename... Args>
  32. struct matcher {
  33. public:
  34. matcher(Args &&... args) : value(std::forward<Args>(args)...) {}
  35. operator bool( ) const { return true; }
  36. bool unmatched( ) const { return ! satisfied; }
  37. template <typename... NArgs>
  38. bool matches(NArgs &&... args) const {
  39. bool const matched = value == std::make_tuple(std::forward<NArgs>(args)...);
  40. satisfied |= matched;
  41. return matched;
  42. }
  43. private:
  44. std::tuple<Args...> value;
  45. mutable bool satisfied = false;
  46. };
  47. template <typename... Args>
  48. matcher<Args...> make_matcher(Args &&... args) {
  49. return matcher<Args...>(std::forward<Args>(args)...);
  50. }
  51. }
  52. #define match( ... ) \
  53. if ( auto const & _matcher_local = \
  54. ::matcher::make_matcher( __VA_ARGS__ ) )
  55. #define with( ... ) \
  56. if ( _matcher_local.unmatched( ) && \
  57. _matcher_local.matches( __VA_ARGS__ ) )
  58. #define else_with( ... ) \
  59. else if ( _matcher_local.matches( __VA_ARGS__ ) )
  60. #define and_with( ... ) \
  61. if ( _matcher_local.matches( __VA_ARGS__ ) )
  62. #define nomatch( ) \
  63. if ( _matcher_local.unmatched( ) )