C ++中的括号和宏重载 [英] Parentheses and macro overloading in C++

查看:120
本文介绍了C ++中的括号和宏重载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码库已有一个宏:

My codebase has an existing macro:

#define SOME_MACRO <macro definition>

对于我要进行的某些更改,我想添加一个带有参数的宏的新版本.

For some changes I'm making, I want to add a new version of the macro that takes an argument.

#define SOME_MACRO(arg1) <macro definition>

我看到这问题从宏的多个参数版本中选择的地址.但是,SOME_MACRO调用还没有括号.它用作SOME_MACRO,而不是SOME_MACRO().有什么方法可以实现宏重载,例如SOME_MACRO调用SOME_MACRO().我试过了:

I see that this question addresses selecting from multiple argument versions of a macro. However, the SOME_MACRO call does not already have parantheses. It's used as SOME_MACRO, not SOME_MACRO(). Is there any way to implement macro overloading such that SOME_MACRO calls SOME_MACRO(). I tried:

#define SOME_MACRO SOME_MACRO()
#define SOME_MACRO(...) <macro definition using __VA_ARGS__>

但这只是让我出现了宏重新定义错误.在呼叫站点上,这是当前的样子:

but that just got me a macro redefinition error. At the call site, this is what it currently looks like:

SOME_MACRO << "This is a test";

我想添加以下形式的新呼叫:

I want to add new calls of the form:

SOME_MACRO(foo) << "This is a test";

我希望两个调用都能正常工作,因为前者已经在代码库中.这些基本上是日志宏,它们创建暴露流的对象.销毁后,他们会写出流内容.

I want both calls to work, since the former is already in the code base. These are basically logging macros, and they create objects that expose a stream. On destruction, they write out the stream contents.

推荐答案

不可能进行宏重载.
在您的情况下,由于一旦定义了SOME_MACRO(...)后就不再需要SOME_MACRO,则可以在预期的(头)文件中执行以下操作:

Macro overloading is not possible.
In your case since you don't want SOME_MACRO anymore once the SOME_MACRO(...) is defined, you may do following in the intended (header) file:

#undef SOME_MACRO  // hopefully it is not a standard macro!
#define SOME_MACRO(...) // use __VA_ARGS__

现在在代码中您可以调用SOME_MACRO(x,y,z);即带有括号.

Now in the code you can call SOME_MACRO(x,y,z); i.e. with parenthesis.

如果要保留代码中的SOME_MACRO,请执行以下操作:

In case if you want to retain SOME_MACRO as it is in the code, then do as following:

#undef SOME_MACRO
#define SOME_MACRO SOME_MACRO_1(<pass arguments here itself>)

请记住,上面传递的参数将随处可见.

Remember that the arguments passed above will be as it is everywhere.

这篇关于C ++中的括号和宏重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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