Iterators: distance versus operator- argument types.

Ian Lance Taylor iant@google.com
Tue Aug 24 14:57:00 GMT 2010


rgamarra <rgamarra@gmail.com> writes:

> int
> main()
> {
>   std::vector<int>::const_iterator i;
>   std::vector<int>::iterator j;
>   i - j;
>   // std::distance(i, j); // not the same iterator types
> }

> Now, the call to operator- succeeds. Is it legal standard-C++?
> Particularly, is that mixing of types in the expression required to be
> possible by the standard? Or is it an gnu-extension? I'm using g++
> (Ubuntu 4.3.3-5ubuntu4) 4.3.3.

There is a conversion from iterator to const_iterator.  So in this case
j is converted to const_iterator in order to make the types the same.

> Now in the sources, I see that (unlike distance) operator- is defined
> with two different template type parameters, which, I understand,
> allow to perform, directly, that mixing.

Specifically to permit mixing iterator and const_iterator, yes.

Ian



More information about the Gcc-help mailing list