为什么 std::next/prev 不像 std::advance 那样按距离模板化?

use*_*436 7 c++ iterator c++11

出于好奇,对 的std::advance()距离类型使用模板参数的基本原理是什么,但difference_type对距离 instd::next()和使用迭代器的基本原理是什么std::prev()

为什么不使用相同的方法(任一方法)?

跟进:

默认的存在n = 1似乎并没有阻止next被模板化,Distance正如下面答案中所建议的那样。这编译:

#include <iterator>
#include <set>

template<typename InputIt,
    typename Distance = typename std::iterator_traits<InputIt>::difference_type>
InputIt my_next(InputIt it, Distance n = 1)
{
    std::advance(it, n);
    return it;
}

int main()
{
    std::set<int> s;
    my_next(s.begin());
    my_next(s.begin(), 10ul);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

dew*_*led 1

需要能够同时编译std::next(it, n)和 ,std::next(it)默认为 1:

template<typename InputIt , typename Distance>
InputIt 
next(InputIt it, Distance n = 1)
{
    std::advance(it, n);
    return it;
}

void foo(int *p)
{
    next(p, 1);         // ok
    next<int*, int>(p); // ok
    next(p);  // error: no matching function for call to 'next(int*&)'
}
Run Code Online (Sandbox Code Playgroud)

gcc bugzilla 中讨论了解决此重载解决问题的可能方法:https://gcc.gnu.org/bugzilla/show_bug.cgi ?id=40497

  • @Meowmere 我不确定我是否理解。第二个模板参数也可以有一个默认值,比如“typename Distance = int”,然后这个答案中的“next(p)”调用就可以编译得很好。 (2认同)