fork download
  1. /** Set max/min using bitwise operations.
  2.  *
  3.  * $ c++ -std=c++14 *.cc && ./a.out
  4.  *
  5.  */
  6. #include <iostream>
  7. #include <type_traits>
  8.  
  9. namespace
  10. {
  11. template <typename T, bool = std::is_unsigned<T>::value> class bitwise_limits {
  12. public:
  13. static constexpr T max() noexcept { return T(); }
  14. static constexpr T min() noexcept { return T(); }
  15.  
  16. };
  17.  
  18. // unsigned specialization
  19. template <typename T>
  20. class bitwise_limits<T, true> {
  21. public:
  22. static constexpr T max() noexcept { return ~T(0); } // all bits set
  23. static constexpr T min() noexcept { return T(0); } // all bits clear
  24. };
  25.  
  26. // signed specialization
  27. template <typename T>
  28. class bitwise_limits<T, false> {
  29. public:
  30. static constexpr T max() noexcept { // all bits set except sign
  31. return bitwise_limits<std::make_unsigned_t<T>>::max() >> 1;
  32. }
  33. static constexpr T min() noexcept {
  34. return ~max(); // all bits clear except sign
  35. }
  36.  
  37. };
  38. }
  39.  
  40.  
  41. int main()
  42. {
  43. std::cout << (int)bitwise_limits<uint8_t>::max() << '\n';
  44. std::cout << (int)bitwise_limits<uint8_t>::min() << '\n';
  45. std::cout << (int)bitwise_limits< int8_t>::max() << '\n';
  46. std::cout << (int)bitwise_limits< int8_t>::min() << '\n';
  47. }
  48.  
Success #stdin #stdout 0s 15240KB
stdin
Standard input is empty
stdout
255
0
127
-128