This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Iterators: distance versus operator- argument types.


Hi all,

I came across with a difference (no pun intended) while calculating
the distance between two iterators. For the sake of concreteness,
consider the following:

#include <iostream>
#include <vector>
#include <iterator>

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

The last commented-out line doesn't compile because (according to
clause 24.3.4 of the C++ standard) std::distance is templated with the
same type parameter in both arguments. So, I understand, the compiler
behaviour is correct in this sense.

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.

What I see in the standard is that (in table 76 from 24.1.5 Random
access iterators) what's required for the expression "b - a" is for a
and b of the same type. Also, in "Table 65—Container requirements"
it's required that iterator is convertible to const_iterator.

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.

namespace __gnu_cxx __attribute__ ((__visibility__ ("default"))) {
  template<typename _IteratorL, typename _IteratorR, typename _Container>
    inline typename __normal_iterator<_IteratorL, _Container>::difference_type
    operator-(const __normal_iterator<_IteratorL, _Container>& __lhs,
       const __normal_iterator<_IteratorR, _Container>& __rhs)
    { return __lhs.base() - __rhs.base(); }
}

Cheers and thanks a lot for the help regarding this issue.

--
Rodolfo Federico Gamarra


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]