tribool.h 5.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. #pragma once
  2. #include <compare>
  3. #define JVALIDATE_TRIBOOL_TYPE(TypeName, True, False, Maybe) \
  4. class TypeName { \
  5. public: \
  6. enum Enum { True, False, Maybe }; \
  7. \
  8. private: \
  9. Enum state_; \
  10. \
  11. public: \
  12. TypeName(bool state) : state_(state ? True : False) {} \
  13. TypeName(Enum state) : state_(state) {} \
  14. \
  15. operator Enum() const { return state_; } \
  16. explicit operator bool() const { return state_ != False; } \
  17. \
  18. friend TypeName operator!(TypeName val) { \
  19. if (val.state_ == Maybe) { \
  20. return Maybe; \
  21. } \
  22. return val.state_ == False ? True : False; \
  23. } \
  24. \
  25. friend TypeName operator|(TypeName lhs, TypeName rhs) { \
  26. if (lhs.state_ == Maybe && rhs.state_ == Maybe) { \
  27. return Maybe; \
  28. } \
  29. if (lhs.state_ == True || rhs.state_ == True) { \
  30. return True; \
  31. } \
  32. return False; \
  33. } \
  34. \
  35. friend TypeName operator&(TypeName lhs, TypeName rhs) { \
  36. if (lhs.state_ == Maybe && rhs.state_ == Maybe) { \
  37. return Maybe; \
  38. } \
  39. if (lhs.state_ == False || rhs.state_ == False) { \
  40. return False; \
  41. } \
  42. return True; \
  43. } \
  44. \
  45. TypeName & operator&=(TypeName rhs) { return *this = *this & rhs; } \
  46. TypeName & operator|=(TypeName rhs) { return *this = *this | rhs; } \
  47. \
  48. friend auto operator==(TypeName lhs, TypeName::Enum rhs) { \
  49. return static_cast<int>(lhs.state_) == static_cast<int>(rhs); \
  50. } \
  51. friend auto operator!=(TypeName lhs, TypeName::Enum rhs) { \
  52. return static_cast<int>(lhs.state_) != static_cast<int>(rhs); \
  53. } \
  54. friend auto operator<=>(TypeName lhs, TypeName rhs) { \
  55. return static_cast<int>(lhs.state_) <=> static_cast<int>(rhs.state_); \
  56. } \
  57. }