问题描述
这是我正在玩的一些 C++ 代码:
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:
宏FOREACH"需要 2 个参数,但只有 1 个给定
如果我将 IN
更改为逗号,则代码会编译.如何让 IN
代替逗号?
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;
}
推荐答案
其他人已经解释了为什么它不能按原样编译.
Others have already explained why it doesn't compile as is.
为了让它工作,你必须给那个 IN
一个机会变成一个逗号.为此,您可以在宏定义中引入额外级别的间接"
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
),并且不能再显式指定逗号.IE.现在这个
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
编译正常,而
FOREACH(int item, ints)
cout << item;
ENDFOREACH
没有.
这篇关于为什么不能编译,如何实现它呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!