如何返回通用迭代器(独立于特定容器)?

Fra*_*ank 7 c++ iterator stl pimpl-idiom

我想设计一个类Foo来存储不同类型的各种数据并返回它们的迭代器。它应该是通用的,因此用户Foo不知道数据是如何存储的(Foo可能正在使用std::setstd::vector其他)。

我很想写一个这样的界面:

class Foo {
  class FooImpl;
  FooImpl* impl_;
public:
  const Iterator<std::string>& GetStrings() const;
  const Iterator<int>& GetInts() const;
};
Run Code Online (Sandbox Code Playgroud)

哪里Iterator有类似这样的东西(比如 .NET 中的迭代器):

template<class T>
class Iterator {
public:
  const T& Value() const = 0;
  bool Done() const = 0;
  void Next() = 0;
};
Run Code Online (Sandbox Code Playgroud)

但我知道这种迭代器在C++中不是标准的,最好像STL那样使用迭代器,这样你就可以在它们上使用STL算法。

我怎样才能做到这一点?(我有需要iterator_traits吗?)

ami*_*mit 1

使用 typedef 返回一个boost::iterator_range. 例如(不要介意名字),

class Container
{
     typedef std::vector<int> Collection; 

     public:
     typedef boost::iterator_range<Collection::iterator> CollectionRange;
     typedef Collection::iterator CollectionIterator;
     Range range() const {
          return make_iterator_range(collection_.begin(), collection_.end());
     }

     private:
     Collection collection_;          
};
Run Code Online (Sandbox Code Playgroud)

用户代码将是

Container c;
// ...
FOREACH(int i, c.range()) { //... }
Container::Range r = c.range();
for(Container::iterator j = r.begin(); j!= r.end(); j++) { // ... }
Run Code Online (Sandbox Code Playgroud)

这不是通用的,但相同的想法可以用于模板。