我目前正在尝试理解各种语言中迭代器的内在机制,即它们的实现方式。
例如,以下类可公开列表接口。
template<class T>
class List
{
public:
virtual void Insert( int beforeIndex, const T item ) throw( ListException ) =0 ;
virtual void Append( const T item ) =0;
virtual T Get( int position ) const throw( ListException ) =0;
virtual int GetLength() const =0;
virtual void Remove( int position ) throw( ListException ) =0;
virtual ~List() =0 {};
};
根据GoF的说法,实现支持不同遍历方式的迭代器的最佳方法是创建一个基本的Iterator类(List的友元),该类具有可以访问List成员的受保护方法。 Iterator的具体实现将以不同的方式处理工作,并通过基本接口访问List的私有和受保护数据。
从这里开始事情变得混乱了。比如,我有一个LinkedList和ArrayList类,它们都派生自List,并且还有相应的迭代器,每个类返回不同的值。那么我该如何实现LinkedListIterator呢?我完全没有思路。此外,基本迭代器类能够从List中检索哪些数据(List仅仅是一个接口,而所有派生类的实现都有很大的差异)?
List
已经被模板化,为什么还要从中派生呢?如果您删除所有的virtual
限定符并提供缺失的定义,那么您已经可以将其用于任何可想象的目的了。 - wilhelmtellstd::stack
是一个适配器,模板化于某些后端容器,例如上述的List
。 - wilhelmtell