Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Foreach implementation in C++, a Poor man's approach

Tags:

c++

There are happy people working with boost and Qt. In my current "embedded" project I have to use home-made container classes. OK, enough complaining.

I've tried to implement an easy and self-contained foreach like that:

#define ForEachString(S,C) TString S;\
        for ( int i=0; i<C.GetSize() && (!!(&(S=C[i]))); ++i  )

It iterates through a string-list which has op[] and GetSize() methods. E.g.:

TStringList tables;
ForEachString( table, tables )
{
  //do sth. with tab.
}

Of cause, the ugly thing is, each container type requires its own macro. Therefore my question: Is it possible to do it container independant and still self contained (all required stuff within the macro definition)?

Regards, Valentin

like image 395
Valentin H Avatar asked Dec 02 '10 20:12

Valentin H


2 Answers

Perhaps you could parameterise on the type T:

#define ForEach(T,S,C) T S;\ 
    for ( int i=0; i<C.GetSize() && (!!(&(S=C[i]))); ++i  ) 

TStringList tables; 
ForEach( TString, table, tables ) 
{ 
  //do sth. with tab. 
} 
like image 183
Greg Hewgill Avatar answered Sep 29 '22 12:09

Greg Hewgill


I would recommend this one

#define ForEachString(S,C) \
  if(bool _j_ = false) ; else
    for (int _i_ = 0; _i_ < C.GetSize() && !_j_; ++_i_, _j_ = !_j_)
      for(S = C[_i_]; !_j_; _j_ = true)

TStringList tables;
ForEachString(TString table, tables)
{
  //do sth. with table
}

The weird actions with _j_ are needed to not break break inside the loop. Best use names like _i_ and _j_ so to not interfere with user's local loop variables.

like image 40
Johannes Schaub - litb Avatar answered Sep 29 '22 13:09

Johannes Schaub - litb