bound_number.hpp 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. //
  2. // bound_number.hpp
  3. // utilities
  4. //
  5. // Created by Sam Jaffe on 10/22/13.
  6. // Copyright (c) 2013 Sam Jaffe. All rights reserved.
  7. //
  8. #pragma once
  9. #include <stdexcept>
  10. struct {} check_bounds;
  11. using check_bounds_t = decltype(check_bounds);
  12. template <class Tp, Tp MINIMUM_VALUE, Tp MAXIMUM_VALUE>
  13. class bound_number final {
  14. private:
  15. public:
  16. static_assert(MINIMUM_VALUE <= MAXIMUM_VALUE, "The minimum value must be less than or equal to the maximum");
  17. typedef Tp value_type;
  18. static constexpr const value_type min = MINIMUM_VALUE;
  19. static constexpr const value_type max = MAXIMUM_VALUE;
  20. bound_number() = default;
  21. bound_number(const bound_number& other) = default;
  22. bound_number(bound_number&& other) = default;
  23. bound_number& operator=(const bound_number& other) = default;
  24. bound_number& operator=(bound_number&& other) = default;
  25. ~bound_number() = default;
  26. bound_number(Tp const & val) :
  27. value(std::max(MINIMUM_VALUE, std::min(MAXIMUM_VALUE, val))) {
  28. }
  29. bound_number(check_bounds_t, Tp const & val) :
  30. value(val) {
  31. if ( val < MINIMUM_VALUE || MAXIMUM_VALUE < val ) {
  32. throw std::out_of_range{"Must construct a value within range"};
  33. }
  34. }
  35. bound_number& operator --() {
  36. if (min < value) { --value; }
  37. return *this;
  38. }
  39. bound_number& operator ++() {
  40. if (value < max) { ++value; }
  41. return *this;
  42. }
  43. bound_number operator --(int) {
  44. bound_number tmp = *this;
  45. operator--();
  46. return tmp;
  47. }
  48. bound_number operator ++(int) {
  49. bound_number tmp = *this;
  50. operator++();
  51. return tmp;
  52. }
  53. operator Tp() const {
  54. return value;
  55. }
  56. private:
  57. Tp value;
  58. };