1

Why doesn't the iterator below satisfy std::input_iterator concept? What did I miss?

template <class T>
struct IteratorSentinel {};

template <class T>
class Iterator
{
public:

    using iterator_category = std::input_iterator_tag;

    using value_type = T;

    using difference_type = std::ptrdiff_t;

    using pointer = value_type*;

    using reference = value_type&;

    Iterator() = default;
    
    Iterator(const Iterator&) = delete;

    Iterator& operator = (const Iterator&) = delete;

    Iterator(Iterator&& other) = default;

    Iterator& operator = (Iterator&& other) = default;

    T* operator-> ();

    T& operator* ();

    bool operator== (const IteratorSentinel<T>&) const noexcept;

    Iterator& operator++ ();

    void operator++ (int);
};

The following static assertion fails:

static_assert(std::input_iterator<Iterator<int>>);

And, for example, the code below does not compile:

template <class T>
auto make_range()
{
    return std::ranges::subrange(Iterator<T>(), IteratorSentinel<T>{});
}

std::ranges::equal(make_range<int>(), std::vector<int>());
1
  • 1
    My Clang gives me constraints not satisfied for alias template 'iter_reference_t' [with _Tp = const Iterator<int>], meaning operator* must work even on const iterators. Commented Sep 17, 2022 at 9:31

1 Answer 1

3

Your operator* is not const-qualified.

The std::input_iterator concept (through the std::indirectly_readable concept) requires that * can be applied to both const and non-const lvalues as well as rvalues of the type and that in all cases the same type is returned.

Sign up to request clarification or add additional context in comments.

2 Comments

Adding const T& operator* () const does not help.
@AlexeyStarinsky "and that in all cases the same type is returned". It must return T&, not const T&.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.