为什么迭代器类型演绎失败
Why does iterator type deduction fail?
为什么这在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,循环缓冲区等
相关文章:
- 如果没有malloc,链表实现将失败
- 模板参数替换失败,并且未完成隐式转换
- 具有默认模板参数的多态类的模板推导失败
- 视图中的参数推导失败:take_while
- 链接到自行创建的dll失败
- 带有特殊路径部分的"std::filesystem::weakly_canonical"失败
- 使用显式模板参数列表和 [temp.arg.explicit]/3 的函数调用的演绎失败
- λ类型演绎失败
- SFINAE使用演绎,但用替换失败
- 可变参数模板构造函数的演绎指南失败
- 模板作为函数模板的参数 - 演绎失败
- 错误:没有匹配的函数调用[…]注意:模板参数演绎/替换失败
- 模板参数演绎/替换失败
- 为什么decltype返回类型在递归模板中失败,而返回类型演绎却工作得很好?
- 为什么这个编译,模板演绎会失败
- c++模板参数演绎失败
- 为什么模板参数演绎/替换在这里失败?
- Boost::odeint演绎/替换失败
- 为什么迭代器类型演绎失败
- 模板参数演绎失败