While experimenting with this stackoverflow answer I encountered a compilation error I don't understand.
With #if 1
the compilation fails with following error log whereas with if 0
the compilation is OK.
Full error log:
Output of x86-64 gcc 11.2 (Compiler #1)
<source>: In function 'void remove(std::vector<T>&, size_t)':
<source>:8:3: error: need 'typename' before 'std::vector<T>::iterator' because 'std::vector<T>' is a dependent scope
8 | std::vector<T>::iterator it = vec.begin();
| ^~~
<source>:8:27: error: expected ';' before 'it'
8 | std::vector<T>::iterator it = vec.begin();
| ^~~
| ;
<source>:9:16: error: 'it' was not declared in this scope; did you mean 'int'?
9 | std::advance(it, pos);
| ^~
| int
<source>: In instantiation of 'void remove(std::vector<T>&, size_t) [with T = int; size_t = long unsigned int]':
<source>:25:9: required from here
<source>:8:19: error: dependent-name 'std::vector<T>::iterator' is parsed as a non-type, but instantiation yields a type
8 | std::vector<T>::iterator it = vec.begin();
| ^~~~~~~~
<source>:8:19: note: say 'typename std::vector<T>::iterator' if a type is meant
Code (available here):
#include <iostream>
#include <vector>
#if 1
template <typename T>
void remove(std::vector<T>& vec, size_t pos)
{
std::vector<T>::iterator it = vec.begin();
std::advance(it, pos);
vec.erase(it);
}
#else
template <typename T>
void remove(std::vector<T>& vec, size_t pos)
{
vec.erase(vec.begin() + pos);
}
#endif
int main()
{
std::vector<int> myvector{ 1,2,3,4 };
remove(myvector, 2);
for (auto element : myvector)
std::cout << ' ' << element;
std::cout << '\n';
return 0;
}
Now if I do what the compiler suggests (typename std::vector<T>::iterator it = vec.begin();
) it compiles, but I don't really understand why typename
is required here.