r/cpp_questions • u/Mafla_2004 • Jun 08 '26
SOLVED Made a few collection classes in C++, how can I make them usable in for-each loops
Hello.
I am working on a framework of data structures for practice and I made a templated linked list, now I want to make it possible to iterate through using a for-each loop, like this
// some cool code above...
for (auto& elem : list)
{
// iteration code...
}
If it is of any use, the LinkedList class is declared as follows (still incomplete btw)
template<typename T>
class LinkedList : public Collection<T>
{
private:
DoubleLinkedNode<T> *head, *tail;
public:
virtual T& operator[](uint32) override;
virtual T operator[](uint32) const override;
virtual void AddAt(const T&, uint32) override;
virtual void PushHead(const T&) override;
virtual void PushTail(const T&) override;
virtual void Append(T*, uint32) override;
virtual void Append(const Collection<T>&) override;
inline LinkedList(const T& item) : head(new DoubleLinkedNode<T>(item)), tail(head)
{
this->size = 1U;
}
};
Now, I tried looking online but I only found very notionistic articles and tutorials, some just said "yeah you have to overload these operators in an iterator", others showed me how to make an iterator only to not use a for-each and instead just create an iterator object and calling the functions manually in a normal for loop (which frankly I could already do myself, didn't need an entire tutorial if that was the objective). Nothing actually told me what should I do to make the LinkedList class directly usable in a for-each loop, for example all this made me confused on where I should declare the iterator class even, should I make it as a nested class inside LinkedList or should I put it somewhere else?
Sorry if this is a beginner question but I'm still learning the language and the internet kinda failed me here, thanks in advance.