如何获取 __COUNTER__ 的最后一个值
我有一个宏,其功能类似于以下内容:
#define MAKE_VALS(...) \
int val1 = 0; \
int val2 = 0; \
:
if(val1 == val2) \
{ \
...
}
并且我需要在单个函数中多次使用它。问题是,由于 val1 和 val2 的多个定义,多次使用它会导致多个定义错误。
将 __COUNTER__
与 ##
一起使用可以解决问题,但我不知道如何为 if 语句获取正确的变量名称?我无法再次使用 __COUNTER__ 因为我会得到下一个值。我需要一种方法来获取 __COUNTER__ 的最后一个值。能做到吗?
附言。我不想用 {}
包围它来解决问题。我在这里简化了真正的问题,并且使用 {}
会导致其他问题(这对我要问的问题并不重要)。
I have a macro that does something similar to the following:
#define MAKE_VALS(...) \
int val1 = 0; \
int val2 = 0; \
:
if(val1 == val2) \
{ \
...
}
and I need to use it multiple times within a single function. The trouble is, using it multiple times causes multiple definition errors due to multiple definitions of val1 and val2.
Using __COUNTER__
with ##
would solve the problem, but I can't see how to get the correct variable names for the if statement? I can't use __COUNTER__
again because I'd get the next value. I need a way to get the last value of __COUNTER__
. Can it be done?
PS. I don't want to surround it with {}
s to fix the problem. I've simplified the real problem here and using {}
s causes other problems (that aren't important to what I'm asking).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
无论其目的是什么,您都可以使用多个级别的宏来实现:
这样,您可以在同一范围内多次使用
MAKE_VALS
,并且每次调用都会创建一组新的变量。请注意,如果没有MAKE_VALS1
,您的变量将被命名为val1__COUNTER__
等,并且额外的级别使其成为实际数字。这是宏观写作中的一个很好的练习,但我同意我之前的人的观点,他们质疑这是否是实现你想要实现的目标的正确方法。但关于这一点已经说得够多了,所以我希望这能解决你的问题。
For whatever the purpose of this is, you can achieve that using several levels of macros:
This way, you can use
MAKE_VALS
more than once in the same scope, and every call will create a new set of variables. Note that withoutMAKE_VALS1
, your variables would be namedval1__COUNTER__
and so on, and the extra level makes it the actual number.It's a nice exercise in macro writing, but I agree with the guys before me who questioned if this is the right way to achieve whatever you're trying to achieve. But enough has been said about that, so I hope this solves your problem.
使用:
将第二个
__LINE__
放在下一行,以避免m
和n
具有相同的值。Use:
Put second
__LINE__
on next line to avoid having same value for bothm
andn
.