pts*_*pts 2 c++ templates function
为什么我会收到编译错误no matching function for call to `f( __gnu_cxx::__normal_iterator > >)'
?
#include <vector>
template<typename T>
void f(const typename std::vector<T>::iterator &) {}
void g() {
std::vector<int> v;
f<int>(v.end()); // Compiles.
f(v.end()); // Doesn't compile, gcc 4.3 can't find any match.
}
Run Code Online (Sandbox Code Playgroud)
最终,我想编写一个仅需要向量迭代器的函数,并且无法编译其他任何内容(带有有意义的错误)。所以这template<typename T>void f(const T&) {}
不是一个好的解决方案,因为它也可以针对其他类型进行编译。
您无法从嵌套类型推导出模板参数。想想,例如,std::vector<T>::size_type
这总是std::size_t
:编译器将如何解决歧义?我意识到您的示例中的情况并非如此,但同样的原则适用。例如, 的迭代器类型std::vector<T>
可以是T*
which 也可以是 的迭代器类型std::array<T, N>
。