为什么这在 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
可以是字面上的 typedef
任何事情,编译器都无能为力。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)