C ++, polymorphism and iterators

I want to have a storage interface (abstract class) and a set of storage implementations (SQLite, MySQL, Memcached ..) for storing objects of a known class and retrieving subsets from the storage.
For me, a clear interface would be the following:

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;
};

And then create Storage implementations that run the interface. Now my problem is this:

  • Iterators cannot be polymorphic since they are returned by value.
  • I cannot just subclass Storage :: iterator for my given storage implementation.
  • I was thinking of having a wrapper iterator that wraps and pimpl over the polymorphic type, which is a subclass of the storage implementation, but then I need to use dynamic memory and allocate it all over the place.

Any clues?

+5
8

, - ?

#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";
    }
}

- Iterator::operator== Iterator::operator-> ( , ).

ConcreteStorage, , . , , Iterable, Storage, Iterable Storage. , , , Iterable, shared_ptr ( Itertable , newIterator shared_ptr, ).

+3

.

, , .

Storage. ( ).

+2

, . (increment, dereference ..), Storage.

+1

, , , , , .

, , . , . , (.. ).

, DTL ( , ).

+1

, ( ).

0

adobe:: any_iterator any_iterator (http://thbecker.net/free_software_utilities/type_erasure_for_cpp_iterators/any_iterator.html). , - any_iterator (return by value, pass by value ..).

0

, , (, -), . . instanciation .

, , . , - (.. instanciation instanciation algorythm). / , . , ++ , . .

0

All Articles