Custom iterator for STL-style container

G

gallows

The container is:

template <typename T>
class Container {
public:
// container methods..

// iterator:
class const_iterator {
public:
const_iterator(T* i)
: pntr(i) { }

const_iterator& operator=
(const_iterator);
const_iterator& operator++();
const_iterator operator++(const_iterator);
const_iterator& operator--();
const_iterator operator--(const_iterator);
bool operator==(const_iterator);
bool operator!=(const_iterator);

private:
T* pntr;
};

const_iterator begin() const;
const_iterator end() const;

private:
std::vector<T> v;
};

// Well... implementation for Container<T>::begin() :
template <typename T>
Container<T>::const_iterator Container<T>::begin() const
{
const_iterator i(&v[0]);
return i;
}

g++ says: "error: expected constructor, destructor, or type conversion
before 'Container'"
Where is it wrong? Which is the right way to do that?

Thanks in advance,

s.
 
P

Pierre Senellart

"gallows" ,comp.lang.c++:
template <typename T>
Container<T>::const_iterator Container<T>::begin() const

Container<T>::const_iterator is a qualified (by Container<T>) and
dependent (on T) name; therefore, you have to prefix it by the keyword
"typename" to disambiguate the fact that it is the name of a type
(Container<T>::const_iterator could very well be the name of a data
member for some T).
 
M

mlimber

The container is:

template <typename T>
class Container {
public:
// container methods..

// iterator:
class const_iterator {
public:
const_iterator(T* i)
: pntr(i) { }

const_iterator& operator=
(const_iterator);
const_iterator& operator++();
const_iterator operator++(const_iterator);

This should be:

const_iterator operator++(int);
const_iterator& operator--();
const_iterator operator--(const_iterator);

This should be:

const_iterator operator--(int);
bool operator==(const_iterator);
bool operator!=(const_iterator);

private:
T* pntr;
};

const_iterator begin() const;
const_iterator end() const;

private:
std::vector<T> v;

};

// Well... implementation for Container<T>::begin() :
template <typename T>
Container<T>::const_iterator Container<T>::begin() const

Add "typename" (see http://womble.decadentplace.org.uk/c++/template-faq.html#type-syntax-error):

typename Container said:
{
const_iterator i(&v[0]);
return i;

}

g++ says: "error: expected constructor, destructor, or type conversion
before 'Container'"
Where is it wrong? Which is the right way to do that?

Cheers! --M
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top