When implementing operator[] how should I include bounds checking?

前端 未结 13 1948
清酒与你
清酒与你 2021-01-19 06:12

First of all I apologize for the long lead up to such a simplistic question.

I am implementing a class which serves as a very long 1 dimensional index on a space fil

13条回答
  •  野的像风
    2021-01-19 06:54

    Another option is to let the caller choose the out-of-bounds policy. Consider:

    template 
    quint16 curvePoint::operator[](size_t index)
    {
        index = OutOfBoundsPolicy(index, dimensions);
        return point[index];
    }
    

    Then you could define several policies that the caller may choose. For example:

    struct NoBoundsCheck {
        size_t operator()(size_t index, size_t /* max */) {
            return index;
        }
    };
    
    struct WrapAroundIfOutOfBounds {
        size_t operator()(size_t index, size_t max) {
            return index % max;
        }
    };
    
    struct AssertIfOutOfBounds {
        size_t operator()(size_t index, size_t max) {
            assert(index < max);
            return index % max;
        }
    };
    
    struct ThrowIfOutOfBounds {
        size_t operator()(size_t index, size_t max) {
            if (index >= max) throw std::domain_error;
            return index;
        }
    };
    
    struct ClampIfOutOfBounds {
        size_t operator()(size_t index, size_t max) {
            if (index >= max) index = max - 1;
            return index;
        }
    };
    

提交回复
热议问题