该代码具有两个简化的向下迭代器CitIt
It公开继承自Cit,以允许像foo2中一样从It转换为Cit

我以为It将从int operator-(const self_type& other) const继承Cit。但事实并非如此。为什么?

如果我使用using operator-;,那会使It继承operator-的两个Cit方法吗?那是错误的。

测试:

#include <vector>

template<typename C>
class Cit {
    typedef Cit<C> self_type;
public:
    Cit(const C& container, const int ix)
            : container_(&container), ix_(ix) {}

    self_type operator-(const int n) const {
        return self_type(*container_, ix_ - n);
    }

    int operator-(const self_type& other) const {
        return ix_ - other.ix_;
    }

    const int& operator*() const { return (*container_)[ix_]; }

protected:
    const C* container_;
    int ix_;
};


template<typename C>
class It : public Cit<C> {
    typedef Cit<C> Base;
    typedef It<C> self_type;
public:
    It(C& container, const int ix)
            : Base::Cit(container, ix) {}

    self_type operator-(const int n) const {
        return self_type(*mutable_a(), ix_ - n);
    }

    int& operator*() const { return (*mutable_a())[ix_]; }

private:
    C* mutable_a() const { return const_cast<C*>(container_); }
    using Base::container_;
    using Base::ix_;
};

template <typename C>
void foo(Cit<C>& it) {}

int main() {
    typedef std::vector<int> V;
    V a = {0, 1, 2, 3, 4, 5};
    It<V> b(a, 2);
    It<V> c(a, 2);
    foo(b); // convert from It to Cit works.
    b - c;  // <----- This doesn't work. Why?
    // Assert that result of (b - 1) is an It instead of a Cit.
    *(b - 1) -= 1;
}

最佳答案

您的It<>::operator-(const int n)隐藏了基类operator-中的所有Cit<>

您需要在using Cit<C>::operator-;中添加It<>,以使这些运算符可见,如下所示:

template<typename C>
class It : public Cit<C> {
    //...
public:
    //....

    using Cit<C>::operator-;

    self_type operator-(const int n) const {
        return self_type(*mutable_a(), ix_ - n);
    }

https://godbolt.org/g/s76SSv

10-08 11:39