【问题标题】:Could not deduce template argument for 'const' ... from int无法从 int 推断出 'const' 的模板参数 ...
【发布时间】:2017-08-08 13:48:06
【问题描述】:

我有一个模板函数

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.第一条错误消息是

错误 C2784 'std::reverse_iterator<_ranit> std::operator +(reverse_iterator<_ranit>::difference_type,const std::reverse_iterator<_ranit> &)': 无法推导出模板参数 对于 'const std::reverse_iterator<_ranit> &' 来自 'int' 算法测试

要使代码 sn-p 工作,我必须进行哪些更改?

【问题讨论】:

  • 你在编造一些东西。到目前为止,您发布的任何内容都不会带来反向迭代器。实际上,您正在做其他事情。这是什么?
  • @AnT 面对一个没有可行候选者的重载集,一些编译器会打印出通过名称查找找到的所有可能的重载以及它们不匹配的原因,包括完全不相关的重载。

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


【解决方案1】:

线

for(It j= first + 2; j < second; j++)

Itstd::vector&lt;int&gt;::iterator 时,这应该不是问题。但是,这不一定适用于所有类型的迭代器。请改用std::advance

另外,j &lt; 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++)

【讨论】:

  • &lt; 也不适用于非随机访问迭代器。还有std::next
猜你喜欢
  • 2019-11-29
  • 2013-02-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多