Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
376 views
in Technique[技术] by (71.8m points)

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

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

#include <iostream>
#include <vector>

#define IN ,
#define FOREACH(x,y) for(unsigned int i=0;i<y.size();i++) { x=y[i];
#define ENDFOREACH }

using namespace std;

int main()
{
    vector<int> ints;
    ints.push_back(3);
    ints.push_back(4);
    ints.push_back(5);
    ints.push_back(6);

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

    return 0;
}

However, I get an error:

macro "FOREACH" requires 2 arguments, but only 1 given

The code compiles if I change the IN to a comma. How can I get the IN to take the place of a comma?

Update: for those interested, here is the final version, which, if I do say so myself, is quite nice.

#include <iostream>
#include <vector>

#define in ,
#define as ,
#define FOREACH_(x,y,z) 
        y x; 
        if(z.size()) x = z[0]; 
        for(unsigned int i=0,item;i<z.size();i++,x=z[i])
#define foreach(x) FOREACH_(x)

using namespace std;

int main()
{
    vector<int> ints;
    ints.push_back(3);
    ints.push_back(4);
    ints.push_back(5);
    ints.push_back(6);

    foreach(item as int in ints)
    {
        cout << item << endl;
    }

    return 0;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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<y.size();i++) { x=y[i]; 
#define FOREACH(x) FOREACH_(x)
#define ENDFOREACH } 

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...