views:

320

answers:

1

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.

+7  A: 

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.

anon
+1. Can I suggest adding the words "inside a template definition" after "when you have this situation"?
j_random_hacker