| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071 |
- //
- // bound_number.hpp
- // utilities
- //
- // Created by Sam Jaffe on 10/22/13.
- // Copyright (c) 2013 Sam Jaffe. All rights reserved.
- //
- #pragma once
- #include <stdexcept>
- struct {} check_bounds;
- using check_bounds_t = decltype(check_bounds);
- template <class Tp, Tp MINIMUM_VALUE, Tp MAXIMUM_VALUE>
- class bound_number final {
- private:
- public:
- static_assert(MINIMUM_VALUE <= MAXIMUM_VALUE, "The minimum value must be less than or equal to the maximum");
-
- typedef Tp value_type;
- static constexpr const value_type min = MINIMUM_VALUE;
- static constexpr const value_type max = MAXIMUM_VALUE;
-
- bound_number() = default;
- bound_number(const bound_number& other) = default;
- bound_number(bound_number&& other) = default;
- bound_number& operator=(const bound_number& other) = default;
- bound_number& operator=(bound_number&& other) = default;
- ~bound_number() = default;
-
- bound_number(Tp const & val) :
- value(std::max(MINIMUM_VALUE, std::min(MAXIMUM_VALUE, val))) {
- }
-
- bound_number(check_bounds_t, Tp const & val) :
- value(val) {
- if ( val < MINIMUM_VALUE || MAXIMUM_VALUE < val ) {
- throw std::out_of_range{"Must construct a value within range"};
- }
- }
-
- bound_number& operator --() {
- if (min < value) { --value; }
- return *this;
- }
-
- bound_number& operator ++() {
- if (value < max) { ++value; }
- return *this;
- }
-
- bound_number operator --(int) {
- bound_number tmp = *this;
- operator--();
- return tmp;
- }
-
- bound_number operator ++(int) {
- bound_number tmp = *this;
- operator++();
- return tmp;
- }
-
- operator Tp() const {
- return value;
- }
- private:
- Tp value;
- };
|