views:

1324

answers:

4
+12  Q: 

Generic iterator

I am trying to find a generic way of accessing a set of containers. I have a standard vector and list in addition to another custom list.

The custom list defines an iterator;

class Iterator: public std::iterator<std::forward_iterator_tag, T> {
    // ...
}

Iterator begin() {
    return (Iterator(root));
}

Iterator end() {
    return (Iterator(NULL));
}

with the appropriate operators overloaded.

Ideally, I would like to do this;

class Foo {
public:
    Foo() {
        std::list<int> x;
        std::vector<int> y;
        custom_list<int> z;

        iter = x.begin(); // OR
        iter = y.begin(); // OR
        iter = z.begin();

        // ...
    };
private:
    std::iterator<int> iter;
};

But obviously these are all iterators of different types. I can assume all the containers are of the same type however.

Is there an elegant way to solve this problem?

A: 

Basically, yes.

I am reading in a ton of data into a container that isn't determined until run-time. Rather than having three iterators which will be used identically (in a simple loop), I was looking for a way to declare a generic iterator of sorts.

Mark
+14  A: 

Here are some articles you might find of interest

Giving STL Iterators a Base Class

Type Erasure for C++ Iterators

any_iterator Class Reference

David Sykes
Thomas Becker (author of the second link above) has a longer article which is excellent: http://www.artima.com/cppsource/type_erasure.html
Adrian
+2  A: 

Better late than never...

The latest issue of C-Vu turned up and guess what was in it: That's right, iterators that do exactly what you wanted.

Unfortunately you need to become a member of the ACCU to view the magazine (the article references the Overload article from 2000 that David links to). But for a measly price a year you get a nice magazine to read, conferences and user groups. When you become a member you can view PDF's of the back issues so what are you waiting for?

graham.reeds
Would have been helpful if you'd mentioned that the article is to be found in vol 20 issue 3 June 08 titled Custom Iterators in C++. nice user picture btw.
danio
+1  A: 

A case of being careful what you ask for. The any_iterator classes you see work on an unbounded set of iterator types. You only have three, which you know up front. Sure, you might need to add a fourth type in the future, but so what if that takes O(1) extra lines of code ?

The big advantage of a closed set of possible contained types is that you have an upper bound on sizeof(), which means you can avoid the heap and the indirection it brings. Basically, stuff them all in a boost::variant and call apply_visitor.

MSalters