Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

foreach not working on list of QPair

Tags:

qt

Using Qt, I want this code to work:

QList<QPair<QString, QString>> list;
foreach (QPair<QString, QString> pair, list)
{
}

instead, I get the error:

'pair' : undeclared identifier

Using a typedef I can make it work, but this is not what I want (unless this is the only thing that works):

typedef QPair<QString, QString> MyPair;
QList<MyPair> list;
foreach (MyPair pair, list)
{
}

Can anyone explain why the first foreach doesn't compile?

like image 643
huysentruitw Avatar asked Apr 19 '13 12:04

huysentruitw


2 Answers

it's not the foreach error. It's declaration error. You declared list like this:

QList<QPair<QString, QString>> list;

while it should this way:

QList<QPair<QString, QString> > list;

Just declare QPair outside of loop:

QPair<QString,QString> pair;
foreach(pair,list){

}
like image 107
Shf Avatar answered Nov 18 '22 07:11

Shf


It is not possible to use template classes inside qt foreach statement which contains more than one template parameter, because comma separator conflicts with comma separator inside macros.

#define add( a, b ) (a + b)

template < typename T1, typename T2 >
struct DATA
{
  static const T1 val1 = 1;
  static const T2 val2 = 2;
};

// Usage
const int c = add( 1, 2 ); // OK
const int d = add( DATA< int, int >::val1 , DATA< int, int >::val2 ); // FAIL

because macros add will interpret "DATA< int" as first argument, and " int >::val1" as second, and so on.

like image 23
Dmitry Sazonov Avatar answered Nov 18 '22 07:11

Dmitry Sazonov