Nested struct in templated class with std::map::const_iterator?
Question
The folowing code generates a syntax error at the line where the iterator is declared:
template <typename T>
class A
{
public:
struct B
{
int x, y, z;
};
void a()
{
std::map<int, B>::const_iterator itr; // error: ; expected before itr
}
std::vector<T> v;
std::map<int, B> m;
};
This only happens when A is a templated class. What's wrong with this code? If I move B out of A, the code compiles fine.
Solution
You need a typename:
typename std::map<int, B>::const_iterator itr;
The iterator is a dependant type (depends on B) and when you have this situation the compiler requires you to clarify it with a typename.
There is a reasonable discussion of the issue here.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow