c++ - 无法从 int 推断出 'const' ... 的模板参数

标签 c++ c++11 templates visual-c++

我有一个模板化函数

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/

相关文章:

c++ - 使用 std::tuple 使用模板的多项式乘法

c++ - 构造函数中的初始化列表可以在模板类中使用吗?

指向具有特定参数的函数的指针的c++ vector

c++ - GMOCK 方法抛出编译错误

c++ - 在特征模板中声明静态自动函数指针

c++ - 模板和内存分配

c++ - std::bind、this 和 QtConcurrent

c++ - 如何在 ACE 中获取本地时间而不是 UTC 时间?

c++ - 0 是十进制文字还是八进制文字?

c++ - 如何将空数组传递给 map ?