I am recently learnign about some std::algorithm internals std::advance receives a number type "Distance", I suppose its internal implementation should look lie this: (tag-dispatch is suggested by [Effective C++])
template<class InputIt, class Distance>
void advance(InputIt& it, Distance n>
{
advance_impl(it, n, Iterator_trait<InputIt>::categary)
}
The Iterator_trait should help to do a tag-dispatch and tell the category of iterator, whether it's random access or sequential
So for random access category, the "impl" should look like
template<class InputIt, class Distance>
void advance_impl(InputIt& it, Distance n>
{
it = it +n
}
And for none-random_access category, impl should look like this? (just my guess)
template<class InputIt, class Distance>
void advance_impl(InputIt& it, Distance n>
{
if(n==0)return
else if(n>0)
{
for(Distance d=0;d<n;++d)
++it
}
else
{
for(Distance d=0;d<n;++d)
--it;
}
}
It's just my guess, I wonder if STL implementation really need to judge if n=0,>0,<0 as for different cases.
My guessed implementation should be much too complex. But what is a more graceful implementation, when the iterator is not random-access category.
I suppose a for loop is needed there, how about the sign of "Distance"?