fork(1) download
  1. #include <iostream>
  2. #include <type_traits>
  3.  
  4. namespace bitfields
  5. {
  6. template <typename Bitfield>
  7. constexpr Bitfield operator& (Bitfield x, Bitfield y) noexcept(true)
  8. {
  9. typedef typename std::underlying_type<Bitfield>::type type;
  10. return Bitfield(type(x) & type(y));
  11. }
  12.  
  13. template <typename Bitfield>
  14. Bitfield& operator&= (Bitfield& x, Bitfield y) noexcept(true)
  15. {
  16. typedef typename std::underlying_type<Bitfield>::type type;
  17. return x = x & y;
  18. }
  19.  
  20. template <typename Bitfield>
  21. constexpr Bitfield operator| (Bitfield x, Bitfield y) noexcept(true)
  22. {
  23. typedef typename std::underlying_type<Bitfield>::type type;
  24. return Bitfield(type(x) | type(y));
  25. }
  26.  
  27. template <typename Bitfield>
  28. Bitfield& operator|= (Bitfield& x, Bitfield y) noexcept(true)
  29. {
  30. typedef typename std::underlying_type<Bitfield>::type type;
  31. return x = x | y;
  32. }
  33.  
  34. template <typename Bitfield>
  35. constexpr Bitfield operator^ (Bitfield x, Bitfield y) noexcept(true)
  36. {
  37. typedef typename std::underlying_type<Bitfield>::type type;
  38. return Bitfield(type(x) ^ type(y));
  39. }
  40.  
  41. template <typename Bitfield>
  42. Bitfield& operator^= (Bitfield& x, Bitfield y) noexcept(true)
  43. {
  44. typedef typename std::underlying_type<Bitfield>::type type;
  45. return x = x ^ y;
  46. }
  47.  
  48. template <typename Bitfield>
  49. constexpr Bitfield operator~ (Bitfield x) noexcept(true)
  50. {
  51. typedef typename std::underlying_type<Bitfield>::type type;
  52. return Bitfield(~type(x));
  53. }
  54.  
  55. template <typename Bitfield>
  56. constexpr bool operator! (Bitfield x) noexcept(true)
  57. {
  58. return !typename std::underlying_type<Bitfield>::type(x);
  59. }
  60.  
  61. template <typename Bitfield>
  62. constexpr bool test(Bitfield x) noexcept(true)
  63. {
  64. return !!x;
  65. }
  66. }
  67.  
  68. namespace bitfields
  69. {
  70. enum class bitfield: unsigned char
  71. {
  72. a = 0x01,
  73. b = 0x02,
  74. c = 0x04
  75. };
  76. }
  77.  
  78. typedef bitfields::bitfield bitfield;
  79.  
  80. int main()
  81. {
  82. bitfield v = bitfield::a | bitfield::b;
  83. v &= bitfield::a;
  84. switch (v) {
  85. case bitfield::a | bitfield::b:
  86. case bitfield::a & bitfield::b:
  87. case bitfield::a ^ bitfield::c:
  88. case ~bitfield::a:
  89. default:
  90. break;
  91. };
  92. if (test(v & bitfield::a)) {
  93. std::cout << "a ";
  94. }
  95. if (test(v & bitfield::b)) {
  96. std::cout << "b ";
  97. }
  98. if (test(v & bitfield::c)) {
  99. std::cout << "c ";
  100. }
  101. std::cout << '\n';
  102. }
Success #stdin #stdout 0s 3296KB
stdin
Standard input is empty
stdout
a