Suppose I have a LimitedValue class which holds a value, and is parameterized on int types \'min\' and \'max\'. You\'d use it as a container for holding values which can on
I'd like to offer an alternate version for Kasprzol's solution: The proposed approach always uses bounds of type int. You can get some more flexibility and type safety with an implementation such as this:
template
class Bounded {
private:
T _value;
public:
Bounded(T value) : _value(min) {
if (value <= max && value >= min) {
_value = value;
} else {
// XXX throw your runtime error/exception...
}
}
Bounded(const Bounded& b)
: _value(b._value){ }
};
This will allow the type checker to catch obvious miss assignments such as:
Bounded b1(1);
Bounded b2(b1); // <-- won't compile: type mismatch
However, the more advanced relationships where you want to check whether the range of one template instance is included within the range of another instance cannot be expressed in the C++ template mechanism.
Every Bounded specification becomes a new type. Thus the compiler can check for type mismatches. It cannot check for more advanced relationships that might exist for those types.