Question about vector iterator in template functions

后端 未结 5 1760
慢半拍i
慢半拍i 2020-12-24 07:54

I\'m trying to learn the STL library and I\'m having a weird problem. This code compiles perfectly:

void Show(vector myvec)
{
    vector

        
相关标签:
5条回答
  • 2020-12-24 08:25

    Some compilers have problems detecting what is a member name and what is a type name, when inside templates. Try writing something like this in the first line of your template function body.

    typename vector<T>::iterator it;

    0 讨论(0)
  • 2020-12-24 08:26

    You need to say typename vector<T>::iterator it.

    On another note, you're passing vectors by value. That means the entire vector gets copied in the function call. void Show(vector<T> const &myvec) and using const_iterator would be wiser.

    0 讨论(0)
  • 2020-12-24 08:36

    You need this:

    typename vector<T>::iterator it;
    

    This tells the compiler that vector<T>::iterator should be treated as a type, something it can't assume since iterator is dependent on what T is.

    0 讨论(0)
  • 2020-12-24 08:49

    Maybe it works using typename vector<T>::iterator it; Your compiler cannot know that there is an inner class iterator.

    0 讨论(0)
  • 2020-12-24 08:49

    In the first instance the parameter, although it uses a template, is not a template, it is a fully defined class (vector<int>)

    In the latter instance the parameter is a template on type T and thus requires typename

    0 讨论(0)
提交回复
热议问题