Making a cike custom foreach macro cleaner

I have my own C ++ macro to emulate a foreach loop:

#define foreach(TYPE, ELEMENT, COLLECTION_TYPE, COLLECTION)\
for(COLLECTION_TYPE::iterator ELEMENT##__MACRO_TEMP_IT = COLLECTION.begin(); ELEMENT##__MACRO_TEMP_IT != COLLECTION.end(); ELEMENT##__MACRO_TEMP_IT++) \
{ TYPE ELEMENT = *(ELEMENT##__MACRO_TEMP_IT);

I know there are alternative ways to make a foreach loop - either using C ++ 11, STL, Qt or Boost foreach, but I'm trying to create my own solution just for fun.

The problem is that this macro either requires completion with two curly braces ("}}"), or omit the first bracket and end with one, for example:

foreach(int, i, std::list<int>, indexes)
{
   //do stuff
}}

or

foreach(int, i, std::list<int>, indexes)

   //do stuff
}

I was wondering: does this have a smart macro, so can I use this macro as follows?

foreach(int, i, std::list<int>, indexes)
{
   //do stuff
}
+4
source share
1 answer
#define foreach(TYPE, ELEMENT, COLLECTION_TYPE, COLLECTION)\
for(COLLECTION_TYPE::iterator ELEMENT##MACRO_TEMP_IT = (COLLECTION).begin(); ELEMENT##MACRO_TEMP_IT != (COLLECTION).end(); ++ELEMENT##MACRO_TEMP_IT)\
for(bool ELEMENT##MACRO_B = true; ELEMENT##MACRO_B;)\
for(TYPE ELEMENT = *(ELEMENT##MACRO_TEMP_IT); ELEMENT##MACRO_B; ELEMENT##MACRO_B = false)

Test:

#include <iostream>
#include <list>

int main()
{
    std::list<int> indexes{1, 2, 3};

    foreach(int, i, std::list<int>, indexes)
    {
        std::cout << i << std::endl;
    }

    foreach(int, i, std::list<int>, indexes)
        std::cout << i << std::endl;

    std::list<std::list<int>> listOfLists{{1, 2}, {3, 4}};
    foreach(std::list<int>&, li, std::list<std::list<int>>, listOfLists)
        foreach(int, i, std::list<int>, li)
            std::cout << i << std::endl;
}

Demo

+2
source

All Articles