Meh*_*dad 1 c++ templates typedef type-deduction
为什么这在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());
}
Run Code Online (Sandbox Code Playgroud)
错误是:
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’
Run Code Online (Sandbox Code Playgroud)
它不起作用的主要原因是因为sandard说T这里是非推断的背景.不推断上下文的原因是因为当你将一些类型传递给函数时,编译器必须实例化每一个可能的std::vector(包括对于这个特定翻译单元中不存在的类型),以便尝试找到一个具有相应的类型.
当然,在这种情况下std::vector,编译器可以包含一些魔术来使其工作,因为类的语义是由标准定义的.但一般来说,
TemplateClass<T>::NestedType可以是任何类型的typedef,编译器也无法做到这一点.
| 归档时间: |
|
| 查看次数: |
907 次 |
| 最近记录: |