I have a class named A
, and in this class I have an iterable container, which I do iterate through following some rules of access -- order, emptiness, and others.
To simplify the following example, lets consider I'm just iterating through the container, but this cannot be done using the built-in container's iterator.
class A {
public:
class iterator {
public:
// Constructor
iterator() {
}
// Destructor
~iterator() {
}
// Advances the iterator
void operator++() {
// Some accessing policy
}
};
private:
std::vector<int> a;
};
Everything works tremendously fine -- and looks very neat --, except that, when I do declare my iterator, I must use typename
-- which I pretty much assume that is used in order to tell the compiler that what I have is a type, and not a class instanciation itself.
Questions:
why do I have to use
typename
when I do:A a; for (typename A::iterator it(...); it != ...; ++it) { }
How are iterators commonly defined, since a vector iterator does not require the
typename
tag? Does it have to do with declaring the vector from the class definition, instead of from the vector itself?std::vector<int> v; for (std::vector<int>::iterator it(v.begin()); it != v.end(); ++it) { }
Are the iterators defined inside the container class -- I guess it's named composition --, or, if not, how is it iterators are added to the namespace of a class, like in:
std::vector<int>::iterator it;