Why won#39;t this compile and how can it be implemented so that it does?(为什么不能编译,如何实现它呢?)
问题描述
这是我正在玩的一些 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 个给定
macro "FOREACH" requires 2 arguments, but only 1 given
如果我将 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
没有.
这篇关于为什么不能编译,如何实现它呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么不能编译,如何实现它呢?
基础教程推荐
- CString 到 char* 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
