【发布时间】:2016-09-20 21:32:39
【问题描述】:
如何编写一个基类和几个派生类的迭代器?
迭代器是否必须返回自身(*this)?
到目前为止,我使用typename X 和static_cast<X&>(*this) 来允许派生类继承从基类返回自身的函数。
This 看起来很丑。有没有更好的办法?
简化代码:
#include <iterator>
#include <iostream>
template <typename T, typename X>
class BaseIterator : public std::iterator<std::input_iterator_tag, T> {
//Not intended to be used directly.
private:
T* p;
protected:
virtual void increment(void)=0;
virtual T* stride_index(int index)=0;
public:
virtual ~BaseIterator(){} //virtual destructor.
X operator++(int) { //takes a dummy int argument
X tmp(static_cast<X&>(*this) );
increment();
return tmp;
}
bool operator==(const X & rhs) { return p==rhs.p; }
} ;
template <typename T>
class ContiguousIterator : public BaseIterator<T, ContiguousIterator<T> > {
private:
T* p;
protected:
inline void increment(void) {++p;}
inline T* stride_index(int index){return p + index;}
public:
virtual ~ContiguousIterator(){} //destructor.
ContiguousIterator(T* x) :p(x) {}
ContiguousIterator(const ContiguousIterator<T> & mit) : p(mit.p) {}
} ;
int main(void){
int i[]={0,1,2,3,4,5};
ContiguousIterator<int> itbegin(i);
ContiguousIterator<int> it(i);
it++;
std::cout << "result: " << (it == itbegin) << std::endl;
}
另一种方法是忘记使用继承来编写更少的代码。只需将返回 *this 的函数复制并粘贴到派生类即可。
我似乎越来越能接受这种选择......
【问题讨论】:
-
另外,
ContiguousIterator有两个不相关的公共T* p成员。那只是混乱。 -
我不知道crtp。 crtp 在这种情况下会有帮助吗?
-
简单修复:将 T* p 更改为私有。无法将其更改为受保护。不知何故。我以前试过。
-
查看 25 次后没有解决方案。为什么?迭代器的继承只是一个坏主意吗?
-
因为不清楚你为什么要做你正在做的事情,这是很多代码解释不佳,而“显而易见”的解决方案需要我进行大量测试和编写对的。但是:完成。
标签: c++ inheritance iterator this crtp