Limiting range of value types in C++

前端 未结 9 818
伪装坚强ぢ
伪装坚强ぢ 2020-11-28 10:33

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

9条回答
  •  醉话见心
    2020-11-28 11:08

    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.

提交回复
热议问题