1

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’
user541686
  • 205,094
  • 128
  • 528
  • 886
  • The workaround is the usual one when a template parameter can't be deduced, give it explicitly: `foo(v.end());` – Mark Ransom Mar 04 '13 at 18:50

2 Answers2

6

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.

James Kanze
  • 150,581
  • 18
  • 184
  • 329
2

Simple.

struct X {};
template<> class std::vector<X> {
    typedef std::vector<int>::iterator iterator;
};

Oops.

Templates are Turing-Complete. You are asking the compiler to infer the arguments from the results. This is impossible in the general case, even ignoring the possibility of non-one-to-one correspondence.

Typically, you take the iterator type itself as template parameter. This permits other random-access iterators like deque, circular buffer, etc.

Puppy
  • 144,682
  • 38
  • 256
  • 465