C ++:容器元素的引用

时间:2014-10-24 15:02:11

标签: c++ casting overloading

我尝试用 operator [] 编写容器多项式,返回 references const references 。但是当我想在引用中使用 const operator [] 时,C ++选择 operator [] 而不使用 const 。我应该将 const operator [] 实现为私有函数并在两个地方使用它,还是有办法让编译器使用const-returning函数?

template <typename T>
class Polynomial {
    std::vector<T> data;

    void DeleteTopZeroes () {
        int degree = Degree ();
        while (degree && !data[degree]) {
            --degree;
        }
        data.resize (degree + 1);
    }

public:
    Polynomial (T constantTerm) {
        data.resize (1);
        data[0] = constantTerm;
    }
    int Degree () const {
        return data.size () - 1 ? data.size () - 1: data[0] ? 0 : -1;
    }

    typedef size_t size_type;
    typedef const T& const_reference;

    const_reference operator[] (size_type degree) const {
        return degree <= Degree () ? data[degree] : 0;
    }

    class reference {
        Polynomial<T>& _polynomial;
        int _degree;

    public:
        reference (Polynomial<T>& polynomial, size_type degree)
            : _polynomial (polynomial)
            , _degree (degree)
        {}
        reference operator= (const T& rhs) {
            if (_degree <= _polynomial.Degree ()) {
                _polynomial.data[_degree] = rhs;
                _polynomial.DeleteTopZeroes ();
            } else if (rhs) {
                _polynomial.data.resize (_degree + 1, 0);
                _polynomial.data[_degree] = rhs;
            }
        }
        operator const T&() const {
            return _polynomial[_degree];
            // compiler uses "reference operator[] (size_type degree)" and stucks on recursion
            // but there is "const_reference operator[] (size_type degree) const"
            // which seems to be more similar, isn't it
        }
    };

    reference operator[] (size_type degree) {
        return reference (*this, degree);
    }
};

1 个答案:

答案 0 :(得分:0)

尝试return static_cast<const Polynomial&>(_polynomial)[_degree];强制编译器选择const版本。

好的哪个演员使用证明是有争议的,所以这是一种没有任何演员阵容的方法。

    operator const T&() const {
        const Polynomial& temp = _polynomial;
        return temp[_degree];
    }