我有一个模板化函数
template<typename It>
void Foo(It first, It second)
{
It third = first;
Bar(first, second, third);
}
调用另一个模板函数
template<typename It>
void Bar(It first,It second,It third)
{
for(It j= first + 2; j < second; j++)
{
third++;
}
}
当我使用代码调用Foo
时
std::list<int> l{ 3, 8, 2, 5, 1, 4, 7, 6 };
Foo(l.begin(), l.end());
我收到几个关于该行的错误
for(It j= first + 2; j < second; j++)
在 Foo 中。第一个错误消息是
Error C2784 'std::reverse_iterator<_RanIt> std::operator +(reverse_iterator<_RanIt>::difference_type,const std::reverse_iterator<_RanIt> &)': could not deduce template argument for 'const std::reverse_iterator<_RanIt> &' from 'int' AlgorithmsTests
我需要更改什么才能使代码片段正常工作?
最佳答案
线路
for(It j= first + 2; j < second; j++)
当 It
时应该不是问题是 std::vector<int>::iterator
。但是,这不一定适用于所有类型的迭代器。使用 std::advance
相反。
此外,j < second
也不适用于非随机访问迭代器。谢谢,@T.C.
用途:
It j = first;
std::advance(j,2);
for( ; j != second; j++)
另一个更优雅的选项(谢谢,@AnT):
for( It j = std::next(first, 2) ; j != second; j++)
关于c++ - 无法从 int 推断出 'const' ... 的模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42850133/