Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't C++ find template function?

Why do I get the compile error 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.
}

Ultimately I want to write a function which takes only a vector iterator, and fails to compile (with a meaningful error) for anything else. So template<typename T>void f(const T&) {} is not a good solution, because it compiles for other types as well.

like image 657
pts Avatar asked Aug 24 '26 01:08

pts


1 Answers

You cannot deduce a template argument from a nested type. Think of, e.g., std::vector<T>::size_type which is always std::size_t: how would the compiler resolve the ambiguity? I realize that's not quite the case in your example but the same principle applies. For example, the iterator type of std::vector<T> can be T* which can also be the iterator type of std::array<T, N>.

like image 59
Dietmar Kühl Avatar answered Aug 26 '26 16:08

Dietmar Kühl