该代码有两个简化的下行迭代器Cit和It。
It公开继承Cit以允许从It到Cit的转换,就像在foo2中一样。
我以为It会继承Cit的int operator-(const self_type& other) const。但事实并非如此。为什么?
如果我使用using operator-;,这会使It从Cit继承两个operator-方法吗?那就错了。
测试:
#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;
}发布于 2018-05-04 19:36:46
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);
}发布于 2018-05-04 19:37:14
如果在派生类中定义一个operator-,则将隐藏(阴影)基类中的所有operator-。
using ...;将向派生类引入名为...的所有内容。但是,基类中的self_type operator-(const int n) const将返回派生类的错误类型。
因此,你必须添加一些锅炉板代码,以使这项工作。
https://stackoverflow.com/questions/50181674
复制相似问题