【问题标题】:Removing extra parentheses from C++ macro从 C++ 宏中删除多余的括号
【发布时间】:2017-10-04 05:19:27
【问题描述】:

我有一堆源代码使用双括号进行一堆宏调用,其中第二个 arg 和 forward 是用于打印语句的可变参数。

   DEBUG((1,"here is a debug"))
   DEBUG((1,"here is %d and %d",42,43))

等等。

我想编写一个可以打印 args 2-... 的宏,但我不知道如何删除多余的括号以便访问 args。

也就是说,这显然不起作用:

#define DEBUG(ignore,...) fprintf(stderr,__VA_ARGS__)

并且以下偷偷摸摸的尝试也失败了('DEBUG2 not defined'):

#define DEBUG2(ignore,...) fprintf(stderr,__VA_ARGS__)
#define DEBUG(...) DEBUG2

如果不编辑所有宏调用以删除括号,我如何定义一个可以执行此操作的宏?

【问题讨论】:

    标签: c++ macros parentheses


    【解决方案1】:

    你可以这样做:

    #define PRINTF(unused, ...) fprintf(stderr, __VA_ARGS__)
    #define DEBUG(arg) PRINTF arg
    

    【讨论】:

    • 是的 - 我只是想通了,虽然你先发布了你的答案,所以你得到了功劳! :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多