2

I whant to iterate in a member function over a list. In this code sample I am getting compiler error in for-line:

Expected ; before it, it not declared, end not declared.

Why? The function is even not used in code!

template <class T> bool Settings::saveSimpleList( QString k, const T & l ){
    //...
    for ( T::ConstIterator it = l.constBegin(), end =l.constEnd(); it != end; ++it )
    {
        QString itemValue = QVariant( *it ).toString();
        //...
    }

    return true;
}

I see, I am missing something in template programming. Thank you for your hints!

outis
  • 75,655
  • 22
  • 151
  • 221
Valentin H
  • 7,240
  • 12
  • 61
  • 111
  • BTW: I voted to reject your proposed edit of adding the `qt` tag. The essence of the question doesn't have any relation to QT. – Jon Mar 05 '11 at 13:20
  • Check out this thread : http://stackoverflow.com/questions/610245/where-to-put-the-template-and-typename-on-dependent-names – Prasoon Saurav Mar 05 '11 at 17:20

2 Answers2

7

Do this:

for (typename T::ConstIterator it = l.constBegin(), end =l.constEnd(); it != end; ++it )
{
    QString itemValue = QVariant( *it ).toString();
    //...
}

When writing T::ConstIterator, the compiler can either interpret that as "the static member ConstIterator of type T" or as "the type defined as ConstIterator by a typedef in type T".

If your intent is the second, as here, you need to add typename to tell the compiler.

Jon
  • 428,835
  • 81
  • 738
  • 806
1

The compiler cannot know that T::ConstIterator is a type (because it does't know what T will be). You can indicate that by adding a typename in front of it.

Bo Persson
  • 90,663
  • 31
  • 146
  • 203