petergottschling / discovering_modern_cpp

Source codes of Discovering Modern C++
203 stars 84 forks source link

advance_test.cpp does not compile after updating to use author's advance implementation #3

Open jlgerber opened 7 years ago

jlgerber commented 7 years ago

When looking at the Function Dispatching example, shown in 4-1, something looks amiss. I tried typing it in as shown, but was quite suspicious of the advance template. Couldn't get it to work, so i pulled the repo and looked at the advance_test.cpp file in c++11 directory. I compiled it as is (more or less) and it worked ( after changing the iterator up a bit. A forward_list isn't going to support reverse iteration, right?.):

auto it= l.begin();
advance(it, 2);
cout << *it << '\n';

However, after setting #if 0 to #if 1 it ceased to compile. I decided to fix what was bothering me. That last advance template is defined in relation to advance. However, I assume that you meant advance_aux; otherwise, what is the point of defining all the specializations? So, I change the template function ( or is it function template ? ):

template <typename Iterator, typename Distance>
inline void advance2(Iterator& i, Distance n)
{
    advance_aux(i, n, typename iterator_category<Iterator>::type());

}

But that didn't work. But something was bugging me about the third line.. A little swearing and googling and i came up with this, which works:

template <typename Iterator, typename Distance>
inline void advance2(Iterator& i, Distance n)
{
    advance_aux(i, n, typename  iterator_traits<Iterator>::iterator_category());
}

It is unfortunate that this doesn't work out of the gate. This example code as printed in the book seems flawed, especially considering there is no real description of what is going on at this point. I bought the book despite concerns raised about code quality in some of the reviews and have found it generally great; hopefully this is an outlier, or perhaps i have misunderstood the issue.