为什么迭代器类型演绎失败

Why does iterator type deduction fail?

本文关键字:失败 演绎 类型 迭代器 为什么      更新时间:2023-10-16

为什么这在c++中不起作用?
为什么我不能像这样限制foo的参数为std::vector<T>::iterator,最好的解决方法是什么?

#include <vector>
template<class T>
void foo(typename std::vector<T>::iterator) { }
int main()
{
    std::vector<int> v;
    foo(v.end());
}

错误是:

In function ‘int main()’:
     error: no matching function for call to ‘foo(std::vector<int>::iterator)’
     note: candidate is:
    note: template<class T> void foo(typename std::vector<T>::iterator)
    note:   template argument deduction/substitution failed:
     note:   couldn’t deduce template parameter ‘T’

它不起作用的主要原因是因为标准是这样规定的这里的T是在一个非推导的上下文中。原因是……上下文没有被推导出来是因为当你将某些类型传递给函数时,编译器必须实例化每个单独的可能的std::vector(包括此处未出现的类型)特定的翻译单位),以试图找到其中之一有对应的类型

当然,在std::vector的情况下,编译器可以包含一些魔法使这个工作,因为类的语义都是由标准定义的。但是一般来说,TemplateClass<T>::NestedType可以是字面上的类型定义

简单。

struct X {};
template<> class std::vector<X> {
    typedef std::vector<int>::iterator iterator;
};

哦。

模板是图灵完备的。您要求编译器从结果中推断参数。这在一般情况下是不可能的,即使忽略非一对一对应的可能性。

通常使用迭代器类型本身作为模板形参。这允许其他随机访问迭代器,如deque,循环缓冲区等