宏中的宏
C++ 中可以将宏放入宏吗?
就像:
#define Something\
#ifdef SomethingElse\ //do stuff \
#endif\
我尝试过,但它不起作用,所以我猜它不起作用,除非有某种语法可以修复它?
Is it possible to put a macro in a macro in c++?
Something like:
#define Something\
#ifdef SomethingElse\ //do stuff \
#endif\
I tried and it didn't work so my guess is it doesn't work, unless there's some sort of syntax that can fix it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
宏,是的。预处理器指令,这是您发布的内容,没有
Macros, yes. Preprocessor directives, which are what you posted, no
不,但您可以通过将
#ifdef
拉出作为顶层,并为 true 和 false 分支使用两个不同的#define Something ...
版本来简单地重构它#ifdef
。No, but you can simply refactor this by pulling the
#ifdef
out as the toplevel, and using two different#define Something ...
versions for the true and false branches of the#ifdef
.你不能在宏中使用预处理器指令,但是如果我们想检查是否定义了SomethingElse并调用不同的宏,你可以像这样完成它(需要c99预处理器和Boost.Preprocessor库) :
如果定义了
SomethingElse
,它将调用MACRO1
,否则它将调用MACRO2
。为此,SomethingElse
必须这样定义:顺便说一句,这在 Visual Studio 中不起作用,因为编译器中存在错误,这里有一个解决方法:http://connect.microsoft.com/VisualStudio/feedback/details/380090/可变参数宏替换
You can't use preprocessor directives in macros, but if we want to check if
SomethingElse
is defined and call a different macro, you could accomplish it like this(requires a c99 preprocessor and Boost.Preprocessor library):If
SomethingElse
is defined it will callMACRO1
, otherwise it will callMACRO2
. For this to work,SomethingElse
has to be defined like this:By the way, this won't work in Visual Studio, because of a bug in their compiler, there is a workaround here: http://connect.microsoft.com/VisualStudio/feedback/details/380090/variadic-macro-replacement
我在 带有内存的 c++ 宏? 中回答了这个问题
不。如果您想检查或更改预处理, 环境,换句话说,要定义预处理子例程而不是字符串替换宏,您需要使用标头,尽管这样做的合法理由很少。
No. I answered this in c++ macros with memory?
If you want to inspect or alter the preprocessing environment, in other words to define a preprocessing subroutine rather than a string-replacement macro, you need to use a header, although the legitimate reasons for doing so are few and far between.