3

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.

e.James
  • 116,942
  • 41
  • 177
  • 214
Dennis
  • 35
  • 2

1 Answers1

8

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.