Re: work round for std::distance's long arm.
David Abrahams wrote:
Louis Lavery <Louis@laver.demon.co.uk> writes:
Without the nested typedefs the following fails to compile
under vc7 and gcc 3.2.
/* distance.cpp */
#include <iterator>
#include <list>
namespace user
{
template<typename Iter,typename Dist> struct Cursor
{
};
template<typename Iter,typename Dist>
Dist distance(
Cursor<Iter,Dist> const&,
Cursor<Iter,Dist> const&)
{
return 0;
}
}
int main()
{
user::Cursor<std::list<int>::iterator,int> cur;
distance(cur,cur); // XXX
return 0;
}
/* distance.cpp end */
Because Cursor's instantiated with an iterator from std, I
guess what happens (at XXX) is the compiler looks in
namespace std
Yes, due to argument-dependent lookup. Because
std::list<int>::iterator is a class in namespace std, std
becomes an associated namespace of the argument, and the
signature of that function is considered during lookup.
and sees something like...
template<class Iter>
typename iterator_traits<Iter>::difference_type
distance<Iter,Iter) {...}
...and so needs to instantiate iterator_traits<Cursor> to
get the return type. But the default iterator_traits
requires its parameter to have nested typedefs for
iterator_category etc. Have I got that right?
Exactly.
But why doesn't SFINAE kick in, and eliminate std::distance from
consideration. Substituting
Cursor< std::list< int >::iterator, int >
for InputIterator in
template< typename InputIterator >
typename iterator_traits< InputIterator >::difference_type
distance( InputIterator first, InputIterator last ) ;
should result in a substitution failure, shouldn't it? Or does
the additional "indirection" (the fact that the typedef which
fails is in iterator_traits, and not in the function declaration
itself) block this?
--
James Kanze GABI Software
Conseils en informatique orient?e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S?mard, 78210 St.-Cyr-l'?cole, France, +33 (0)1 30 23 00 34
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]