我目前正在尝试理解各种语言中迭代器的内在性,即它们实现的方式。在C++中编写我自己的stl-like迭代器实现
例如,有以下类暴露列表界面。
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 {};
};
根据四人帮,实现能够支持不同类型的遍历的迭代器的最佳方式是创建基本的迭代器类(列表的朋友)与可访问列表的成员保护的方法。 Iterator的具体实现将以不同的方式处理作业,并通过基本接口访问List的私有和受保护数据。
从这里开始,事情变得混乱。说,我有类LinkedList和ArrayList,都从List派生,并且还有相应的迭代器,每个类都返回。我怎样才能实现LinkedListIterator?我完全没有想法。基类迭代器类可以从列表中检索什么样的数据(这是一个纯粹的接口,而所有派生类的实现差别很大)?
Boost迭代器库是一个很好的信息来源,并且开发了新的迭代器类型/特性http://www.boost.org/doc/libs/1_42_0/libs/iterator/doc/index.html – Hippicoder 2010-04-16 22:26:32
这种气味如Java/C#代码。通常,好的C++看起来不像Java或C#。 – 2010-04-16 22:51:39
为什么你想从'List'派生,如果它是模板化的?如果删除所有'虚拟'限定符并提供缺少的定义,则可以将其用于任何可想到的目的。 – wilhelmtell 2010-04-17 02:27:31