小编use*_*366的帖子

C++迭代器和继承

快速询问下面实现迭代器的最佳方法是什么:

假设我有一个模板化的基类'List'和两个子类"ListImpl1"和"ListImpl2".基类的基本要求是可迭代的,即我可以这样做:

for(List<T>::iterator it = list->begin(); it != list->end(); it++){
   ...
}
Run Code Online (Sandbox Code Playgroud)

我也想允许迭代器添加,例如:

for(List<T>::iterator it = list->begin()+5; it != list->end(); it++){
   ...
}
Run Code Online (Sandbox Code Playgroud)

所以问题是ListImpl1的迭代器的实现将与ListImpl2的迭代器的实现不同.我通过使用包含指向ListIteratorImpl的指针的包装器ListIterator来解决这个问题,该指针包含子类ListIteratorImpl2和ListIteratorImpl2,但它们都变得非常混乱,特别是当您需要在ListIterator中实现operator +时.

有没有想过更好的设计来解决这些问题?

c++ inheritance templates iterator

5
推荐指数
1
解决办法
4354
查看次数

标签 统计

c++ ×1

inheritance ×1

iterator ×1

templates ×1