如何編寫基類和迭代器的幾個派生類?迭代器繼承和繼承*這個
迭代器是否必須返回自己(* 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會有幫助嗎? – rxu
簡單修復:將T * p改爲私有。無法將其更改爲受保護的。不知何故。我曾嘗試過。 – rxu