确定operator []用途的目的

Max*_*xpm 2 c++ methods class operator-overloading operators

假设我的容器类中有以下方法:

Datatype& operator[](const unsigned int Index) // I know this should use size_t instead.
{
    return *(BasePointer + Index); // Where BasePointer is the start of the array.
}
Run Code Online (Sandbox Code Playgroud)

我想对MyInstance[Index] = Value用法实现某种边界检查,以便当用户尝试更改其范围之外的值时,容器会自动调整大小.但是,如果用户试图访问容器范围之外的值,我想要发生其他事情,例如MyVariable = MyInstance[Index].如何检测如何operator[]使用?

Kon*_*lph 5

草图:

返回代理对象而不是实际的数据条目.然后,代理对象定义operator =处理赋值情况,并定义用于读出情况的隐式转换运算符.

template <typename T>
class AccessorProxy {
  friend class Container<T>;
public:
    AccessorProxy(Container<T>& data, unsigned index)
        : data(data), index(index) { }
    void operator =(T const& new_value) {
        // Expand array.
    }
    operator const T&() const {
        // Do bounds check.
        return *(data.inner_array + index);
    }
private:
    AccessorProxy(const AccessorProxy& rhs)
     : data(rhs.data), index(rhs.index) {}
    AccessorProxy& operator=(const AccessorProxy&);
    Container<T>& data;
    unsigned index;
};

template <typename T>
class ConstAccessorProxy {
  friend class Container<T>;
public:
    ConstAccessorProxy(const Container<T>& data, unsigned index)
        : data(data), index(index) { }
    operator const T&() const {
        // Do bounds check.
        return *(data.inner_array + index);
    }
private:
    ConstAccessorProxy(const ConstAccessorProxy& rhs)
     : data(rhs.data), index(rhs.index) {}
    ConstAccessorProxy& operator=(const ConstAccessorProxy&);
    const Container<T>& data;
    unsigned index;
};

AccessorProxy<Datatype> operator[](const unsigned int Index)
{
    return AccessorProxy<Datatype>(*this, Index);
}
ConstAccessorProxy<Datatype> operator[] const (const unsigned int Index)
{
    return ConstAccessorProxy<Datatype>(*this, Index);
}
Run Code Online (Sandbox Code Playgroud)

访问者类可能需要成为容器类的朋友.

找到避免代码重复的方法留给读者练习. :)