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
没有.
这篇关于为什么不能编译,如何实现它呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么不能编译,如何实现它呢?


基础教程推荐
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 从 std::cin 读取密码 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- Windows Media Foundation 录制音频 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01