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)
需要能够同时编译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