C++,多态和迭代器

Ark*_*nez 5 c++ polymorphism iterator class subclass

我想要一个存储接口(抽象类)和一组存储实现(SQLite,MySQL,Memcached ..),用于存储已知类的对象并从存储中检索子集.
对我来说,明确的界面是:

class Storable{int id; blah; blah; blah; string type;};
class Storage{
    virtual Storage::iterator get_subset_of_type(string type) = 0;
    virtual Storage::iterator end)_ = 0;
    virtual void add_storable(Storable storable) = 0;
};
Run Code Online (Sandbox Code Playgroud)

然后创建实现接口的存储实现.现在,我的问题如下:

  • 迭代器不能是多态的,因为它们是按值返回的.
  • 我不能只为我给定的Storage实现子类化Storage :: iterator
  • 我想过有一个包装迭代器,它包装并对存储实现子类的多态类型进行pimpl,但后来我需要使用动态内存并分配到所有地方.

任何提示?

Ste*_*sop 3

如果你想要一个用于迭代的虚拟接口,像这样的东西?

#include <iostream>
#include <iterator>

struct Iterable {
    virtual int current() = 0;
    virtual void advance() = 0;
  protected:
    ~Iterable() {}
};

struct Iterator : std::iterator<std::input_iterator_tag,int> {
    struct Proxy {
        int value;
        Proxy(const Iterator &it) : value(*it) {}
        int operator*() { return value; }
    };
    Iterable *container;
    Iterator(Iterable *a) : container(a) {}
    int operator*() const { return container->current(); }
    Iterator &operator++() { container->advance(); return *this; }
    Proxy operator++(int) { Proxy cp(*this); ++*this; return cp; }
};

struct AbstractStorage : private Iterable {
    Iterator iterate() {
        return Iterator(this);
    }
    // presumably other virtual member functions...
    virtual ~AbstractStorage() {}
};

struct ConcreteStorage : AbstractStorage {
    int i;
    ConcreteStorage() : i(0) {}
    virtual int current() { return i; }
    virtual void advance() { i += 10; }
};

int main() {
    ConcreteStorage c;
    Iterator x = c.iterate();
    for (int i = 0; i < 10; ++i) {
        std::cout << *x++ << "\n";
    }
}
Run Code Online (Sandbox Code Playgroud)

这不是一个完整的解决方案 - 我还没有实现Iterator::operator==,或者Iterator::operator->(如果包含的类型是类类型,则需要后者)。

我将状态存储在 ConcreteStorage 类中,这意味着我们不能同时在同一个存储上有多个迭代器。因此,可能Iterable需要有另一个 Storage 虚拟函数来返回新的Iterable. 事实上,它只是一个输入迭代器,这意味着迭代器的副本都可以指向相同的Iterable,因此可以使用 a 进行管理shared_ptr(并且要么Itertable应该有一个虚拟析构函数,要么 newIterator 函数应该返回shared_ptr,或两者都返回)。