R zu
R zu

Reputation: 2064

Iterator method fails to inherit from Const_iterator

The code has two simplified down iterators Cit and It.

It publicly inherits from Cit to allow conversion from It to Cit as in foo2.

I thought It would inherit int operator-(const self_type& other) const from Cit. But that is not the case. Why?

If I use using operator-;, will that make It inherits both of the two operator- methods from Cit? That would be wrong.

Test:

#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;
}

Upvotes: 2

Views: 270

Answers (2)

Bo Persson
Bo Persson

Reputation: 92211

If you define one operator- in the derived class, that will hide (shadow) all operator- from the base class.

A using ...; will bring in everything with the name ... to the derived class. However, self_type operator-(const int n) const from the base class will return the wrong type for the derived class.

So you have to add some boiler-plate code to make this work.

Upvotes: 2

Mihayl
Mihayl

Reputation: 3911

Your It<>::operator-(const int n) hides all operator- from the base class Cit<>.

You need to add using Cit<C>::operator-; to It<> to make these operators visible like this:

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

Upvotes: 2

Related Questions