PDA

View Full Version : help with templates please



GrahamLabdon
4th February 2011, 16:57
Hi
I have the following code defining a template class


template<class T>
class TemplateClass
{
public:
TemplateClass();
virtual ~TemplateClass() {}
void add (T key, QString value);
void get(QStringList &theStrings) const;

private:
QMap<T,QString> m_strings;

};

template<class T> TemplateClass<T>::TemplateClass()
{

}

template<class T> void TemplateClass<T>::add (T key, QString value)
{
m_strings[key] = value;
}

template<class T> void TemplateClass<T>::getComboBoxStrings(QStringList &theStrings) const
{
QMap<T,QString>::iterator it;


When compiled I get the following error regarding the declaration of the iterator



MyClass.h: In member function 'void TemplateClass<T>::getComboBoxStrings(QStringList&) const':
MyClass.h:74: error: expected ';' before 'it'


Could someone tell me why this is and error

stampede
4th February 2011, 17:16
QMap<T,QString>::iterator it;
Because compiler does not know that "iterator" is a typename. You need to specify that:

typename QMap<T,QString>::iterator it;

----------------
I see that g++ (v 4.5.2) produces a nice message:

template <class C> class Test{
public:
void fun();
};

template<class C> void Test<C>::fun(){
C::iterator it;
}

// error: need 'typename' before 'C:: iterator' because 'C' is a dependent scope

mcosta
4th February 2011, 17:29
Use the typename keyword.



template<class T> void TemplateClass<T>::getComboBoxStrings(QStringList &theStrings) const
{
typename QMap<T,QString>::const_iterator it;


When you use a "compile time unresolved class" (class defined by a template argument) you must suggest the compiler that this class has a type named "const_iterator"