Roomba
Roomba

Reputation: 53

Setting a maximum possible value to a variable C++

it's supposed to be an easy question, but i couldnt find the answer on google. So, how do i assign a maximum possible value to a variable? So i want my variable to be no more than 10 as apossible value no matter what

int example;
example = ?;

Upvotes: 2

Views: 1340

Answers (1)

Jarod42
Jarod42

Reputation: 218268

You might create a custom class to handle your needs, something like:

template <int Min, int Max>
class BoundedValue
{
public:
    BoundedValue(int value = Min) : mValue(Min) { set_value(value); }

    int get_value() const { return mValue; }
    void set_value(int value) {
        if (value < Min || Max < value) {
            throw std::out_of_range("!"); // Or other error handling as clamping
            // value = std::clamp(value, Min, Max);
        }
        mValue = value;
    }

    BoundedValue& operator= (int value) { set_value(value); }

    BoundedValue& operator ++() { set_value(mValue + 1); return *this; }
    BoundedValue operator ++(int) { auto tmp = *this; ++*this; return tmp; }

    // other convenient functions

    operator int() const { return mValue; }

private:
    int mValue = Min;
};

And then use it:

BoundedValue<0, 10> example;

++example;
example = 11; // "Error"

Upvotes: 5

Related Questions