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
没有.
这篇关于为什么不能编译,如何实现它呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么不能编译,如何实现它呢?
基础教程推荐
- 常量变量在标题中不起作用 2021-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 这个宏可以转换成函数吗? 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
