这应该是一个简单的问题,但我无法在谷歌上找到答案。那么,我如何为变量分配最大可能值?所以我希望我的变量不超过 10 作为可能的值,无论如何
int example;
example = ?;
Run Code Online (Sandbox Code Playgroud)
您可以创建一个自定义类来处理您的需求,例如:
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;
};
Run Code Online (Sandbox Code Playgroud)
然后使用它:
BoundedValue<0, 10> example;
++example;
example = 11; // "Error"
Run Code Online (Sandbox Code Playgroud)