Why won't this compile and how can it be implemented so that it does?

后端 未结 6 793
挽巷
挽巷 2020-12-21 12:30

Here is some C++ code I\'m playing around with:

#include 
#include 

#define IN ,
#define FOREACH(x,y) for(unsigned int i=0;i&l         


        
6条回答
  •  粉色の甜心
    2020-12-21 13:00

    Others have already explained why it doesn't compile as is.

    In order to make it work you have to give that IN a chance to turn into a comma. For that you can introduce an extra level of "indirection" in your macro definition

    #define IN , 
    #define FOREACH_(x,y) for(unsigned int i=0;i

    In this case you'll have to use some substitute for comma (like your IN) and can no longer specify comma explicitly. I.e. now this

    FOREACH(int item IN ints) 
        cout << item; 
    ENDFOREACH 
    

    compiles fine, while

    FOREACH(int item, ints) 
        cout << item; 
    ENDFOREACH 
    

    does not.

提交回复
热议问题