3

I am creating a template class in C++, and am using std::list in it. For some reason, my compiler doesn't like how I'm trying to declare and construct an iterator for the list.

In my HashTable.h file I have:

template <typename T> class HashTable {
    bool find(T thing) {
        // some code
        list<T>::iterator iter;
        for (iter = table[index].begin(); iter != table[index].end(); ++iter) {
            // some more code
        }
    }

}

And it gives me HashTable.h:77: error: expected ';' before "iter" as an error message.

What's the proper syntax for the iterator?

Or is that right, and I need to create an iterator class for each of the classes I intend to use in my HashTable template? If so, that would suck...

Mar
  • 7,765
  • 9
  • 48
  • 82
  • 1
    Add a `typename`. There's duplicates of this out there somewhere. [This might be a good read](http://stackoverflow.com/questions/610245/where-and-why-do-i-have-to-put-the-template-and-typename-keywords) – chris Jun 09 '12 at 22:42
  • 1
    You are missing a bracket after the for loop. – Cole Tobin Jun 09 '12 at 22:46
  • @Cole - That's true, though in my full code it is present. Good eye! – Mar Jun 09 '12 at 22:52

1 Answers1

7

You need to use typename to tell the compiler that list<T>::iterator is indeed a type in this context.

typename list<T>::iterator iter;

The reasons are fairly obscure; see the C++ FAQ for more details: http://www.parashift.com/c++-faq-lite/templates.html#faq-35.18.

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
  • I remember the first time I stumbled upon that and, as the FAQ mentioned, it did in fact hurt my head. – Ed S. Jun 09 '12 at 22:56
  • Even my TAs were surprised by that one. Apparently it wasn't mentioned in class. – Mar Jun 17 '12 at 06:02