mardi 28 avril 2020

How to overload dereference operator of std::list for range-based for?

I am trying to handle std::list of pointer type, like this:

std::list<int*> pNums;

Originally, iterating this container with range-based for loop will look like this :

for(int* pNum : pNums)
{
    std::cout << (*pNum) << std::endl;
}

However, I want to iterate this container with a value, not a pointer, like below:

for(int num : Range(pNums))
{
    std::cout << num << std::endl;
}

| Here, Range is a custom wrapping-class of std::list<int*>, something should be defined in this manner, I guess:

class Range
{
    Range(std::list<int*>& _list) : list(_list) {}
    std::list<int*>& list;

    // Basically inherit the original iterator
    class custom_const_iterator : std::list<int*>::const_iterator
    {
        // Define an overloaded dereference operator
        const int& operator*() const
        {
            ...
        }
        ...
    };

public:
    custom_const_iterator begin() { return ...; }
    custom_const_iterator end()   { return ...; }
};

So, my question is, what should I write down for class Range?

Aucun commentaire:

Enregistrer un commentaire