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

前端 未结 13 2134
清酒与你
清酒与你 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 07:06

    Thanks to the comment on the C# feature in the post of Daniel Daranas I have managed to figure out a possible solution. As I stated in my question I am using the Qt libraries. There for I can use QVariant. QVariant can be set to an invalid state that can be checked by the function receiving it. So the code would become something like:

    QVariant curvePoint::operator[](size_t index){
        QVariant temp;
        if(index > dimensions){
            temp = QVariant(QVariant::Invalid);
        }
        else{
            temp = QVariant(point[index]);
        }
    
        return temp;
    }
    

    Of course this has the potential of inserting a bit of gnarly overhead into the function so another possibility is to use a pair template.

    std::pair curvePoint::operator[](size_t index){
        std::pair temp;
        if(index > dimensions){
            temp.second = false;
        }
        else{
            temp.second = true;
            temp.first = point[index];
        }
        return temp;
    }
    

    Or I could use a QPair, which has exactly the same functionality and would make it so that the STL need not be linked in.

提交回复
热议问题