Xie Qing
Xie Qing

Reputation: 81

How to make "auto" type deduction compatible with range-based "for"?

I am learning to make the self-defined class compatible with the range-based 'for' loop.

Given the range class:

class range
{
private:

    range_iterator m_begin;
    range_iterator m_end;

public:

    range()
    :
        m_begin(0),
        m_end(9)
    {}

    range_iterator begin()
    {
        return m_begin;
    }

    range_iterator end()
    {
        return m_end;
    }

};

And the iterator:

class range_iterator
{
public:

    using iterator_category = std::input_iterator_tag;
    using difference_type   = std::ptrdiff_t;
    using value_type        = int;
    using pointer           = int*;
    using reference         = int&;


    range_iterator(int val)
    :
        m_int(val)
    {}

    int value() const
    {
        return m_int;
    }

    range_iterator& operator++()
    {
        ++m_int;
        return *(this);
    }

    int operator*()
    {
        return m_int;
    }

    bool operator!=(const range_iterator &rhs)
    {
        return ( m_int != rhs.value() );
    }

private:

    int m_int;

};

And the main function:

int main()
{
    range r0;

    for (auto r : r0)
    {}

    return 0;
}

The problem is that r is 'auto' deduced as 'int' type.

How to make the 'auto' type deduction of r to be 'range_iterator' ?

I am confused why the type of r is not the same as returned by range::begin()/end()

Upvotes: 0

Views: 71

Answers (0)

Related Questions