为什么不编译,如何实现它呢? [英] Why won't this compile and how can it be implemented so that it does?

查看:92
本文介绍了为什么不编译,如何实现它呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我正在使用的一些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 

没有.

这篇关于为什么不编译,如何实现它呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆