【问题标题】:What does ##__VA_ARGS__ mean?##__VA_ARGS__ 是什么意思?
【发布时间】:2019-03-24 07:08:12
【问题描述】:

我想知道##在这个宏定义中做了什么:

#define debug(M, ...) fprintf(stderr,M "\n",##__VA_ARGS __)

我用谷歌搜索了一个答案,我想出了以下内容。

如果没有给宏提供变量参数,## 将删除逗号。所以,如果像这样调用宏

debug("message");

没有引号,它被扩展为

fprintf(stderr,"message");

不是

fprintf(stderr,"message",);

为什么要去掉逗号?

【问题讨论】:

    标签: c++ macros preprocessor variadic-macros


    【解决方案1】:

    这是 gcc 引入的一种不可移植的语法,专门用于处理根本不传递参数的极端情况。 如果没有##,它会抱怨结尾的逗号是语法错误。

    https://gcc.gnu.org/onlinedocs/gcc/Variadic-Macros.html

    C++20 为此引入了__VA_OPT__https://en.cppreference.com/w/cpp/preprocessor/replace

    【讨论】:

    • 所以它与 ## 的一般行为无关,连接,对吧?
    • 是的,它只是在滥用那个运营商。
    • 从 C++20 开始,您将能够以标准化的方式执行此操作:#define debug(M, ...) fprintf(stderr,M "\n" __VA_OPT__(,) __VA_ARGS __)
    • @CarloWood 看来VS2017不支持__VA_OPT__(,)
    • @JohannGerell 是的,我只是想明确和大胆地说明,即使我拥有的 Visual Studio 2017 版的专业版也不支持我在乞求中任意认为的这个宏。 .....
    【解决方案2】:

    来自https://en.cppreference.com/w/cpp/preprocessor/replace

    Note: some compilers offer an extension that allows ## to appear after a
    comma and before __VA_ARGS__, in which case the ## does nothing when the 
    variable arguments are present, but removes the comma when the variable
    arguments are not present: this makes it possible to define macros such as
    fprintf (stderr, format, ##__VA_ARGS__)
    

    【讨论】:

      猜你喜欢
      • 2014-11-21
      • 1970-01-01
      • 1970-01-01
      • 2011-08-12
      • 2017-06-11
      • 2018-03-05
      • 2023-03-27
      • 1970-01-01
      • 2013-03-09
      相关资源
      最近更新 更多