Adrian
Adrian

Reputation: 10911

Is there a reason why make_reverse_iterator(make_reverse_iterator(it)) results in a different type?

I would think that:

static_assert(is_same_v<
    decltype(make_reverse_iterator(make_reverse_iterator(it)))
  , decltype(it)>);

would compile, but it doesn't. Is there some reason why this is? I can see this as potentially resulting in larger generated code when writing templates.

This isn't that difficult to implement:

template <typename T>
T make_reverse_iterator(reverse_iterator<T> it) {
  return it.base();
}

and would result in a smaller binary if double or more reversals are done when calling a template function, especially if that function were to say call itself recursively using a reverse_iterator of what it was called with without complicating the code with other specializations.

Upvotes: 7

Views: 657

Answers (1)

Nicol Bolas
Nicol Bolas

Reputation: 473262

There's a simple question whose answer explains this:

Is the return value of make_reverse_iterator a reverse_iterator?

See, a reverse iterator is not just an iterator that runs backwards. It's a type. Or rather, it's a template which generates a family of types. And that template is expected to provide certain behavior; that behavior is what makes it a reverse iterator.

And this is behavior that is not required to be provided by a non-reverse_iterator type. A reverse_iterator<reverse_iterator<I>> is not the same thing as I. You can't get the base of I, for example.

If a user calls make_reverse_iterator, it is their right to expect that they will get a reverse_iterator, with all the powers and privileges provided by that template. To return anything else would be tantamount to lying to the user.

What you seem to want is make_iterator_go_backwards: a function that returns some iterator type that goes backwards through the sequence. And that's a valid thing to want.

But that thing is not spelled make_reverse_iterator. If you have a function called, make_some_type, it should return some_type.

Upvotes: 1

Related Questions