首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Iterator方法无法从Const_iterator继承

Iterator方法无法从Const_iterator继承
EN

Stack Overflow用户
提问于 2018-05-04 19:08:31
回答 2查看 184关注 0票数 2

该代码有两个简化的下行迭代器CitIt

It公开继承Cit以允许从ItCit的转换,就像在foo2中一样。

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

如果我使用using operator-;,这会使ItCit继承两个operator-方法吗?那就错了。

测试:

代码语言:javascript
复制
#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;
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-05-04 19:36:46

It<>::operator-(const int n)将所有operator-隐藏在基类Cit<>中。

您需要将using Cit<C>::operator-;添加到It<>以使这些操作符可见,如下所示:

代码语言:javascript
复制
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

票数 2
EN

Stack Overflow用户

发布于 2018-05-04 19:37:14

如果在派生类中定义一个operator-,则将隐藏(阴影)基类中的所有operator-

using ...;将向派生类引入名为...的所有内容。但是,基类中的self_type operator-(const int n) const将返回派生类的错误类型。

因此,你必须添加一些锅炉板代码,以使这项工作。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50181674

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档