Search code examples
c++templatestypedeftype-deduction

Why does iterator type deduction fail?


Why does this not work in C++?
Why can't I restrict foo's parameter to std::vector<T>::iterator like this, and what is the best workaround?

#include <vector>

template<class T>
void foo(typename std::vector<T>::iterator) { }

int main()
{
    std::vector<int> v;
    foo(v.end());
}

The error is:

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’

Solution

  • The main reason it doesn't work is because the sandard says that the T here is in a non-deduced context. The reason why the context is not deduced is because when you pass some type to the function, the compiler would have to instantiate every single possible std::vector (including for types not present in this particular translation unit) in order to try to find one which had a corresponding type.

    Of course, in case of std::vector, the compiler could contain some magic to make this work, since the semantics of the class are defined by the standard. But generally, TemplateClass<T>::NestedType can be a typedef to literally anything, and there's nothing the compiler can do about it.