• c++11 : Variadic Macros(变长参宏)


    Variadic macros are function-like macros that contain a variable number of arguments.

    Remarks

     

    To use variadic macros, the ellipsis may be specified as the final formal argument in a macro definition, and the replacement identifier __VA_ARGS__ may be used in the definition to insert the extra arguments. __VA_ARGS__ is replaced by all of the arguments that match the ellipsis, including commas between them.

    The C Standard specifies that at least one argument must be passed to the ellipsis, to ensure that the macro does not resolve to an expression with a trailing comma. The Visual C++ implementation will suppress a trailing comma if no arguments are passed to the ellipsis.

    Example

     
     
    // variadic_macros.cpp
    #include <stdio.h>
    #define EMPTY
    
    #define CHECK1(x, ...) if (!(x)) { printf(__VA_ARGS__); }
    #define CHECK2(x, ...) if ((x)) { printf(__VA_ARGS__); }
    #define CHECK3(...) { printf(__VA_ARGS__); }
    #define MACRO(s, ...) printf(s, __VA_ARGS__)
    
    int main() {
        CHECK1(0, "here %s %s %s", "are", "some", "varargs1(1)
    ");
        CHECK1(1, "here %s %s %s", "are", "some", "varargs1(2)
    ");   // won't print
    
        CHECK2(0, "here %s %s %s", "are", "some", "varargs2(3)
    ");   // won't print
        CHECK2(1, "here %s %s %s", "are", "some", "varargs2(4)
    ");
    
        // always invokes printf in the macro
        CHECK3("here %s %s %s", "are", "some", "varargs3(5)
    ");
    
        MACRO("hello, world
    ");
    
        MACRO("error
    ", EMPTY); // would cause error C2059, except VC++ 
                                 // suppresses the trailing comma
    }
    

    Output

     
     
     
    here are some varargs1(1)
    here are some varargs2(4)
    here are some varargs3(5)
    hello, world
    error
  • 相关阅读:
    要使用springtest来进行单元测试 否则将无法注入 applicationContext.xml
    关键词的重要性
    发卡可以以交叉方式佩戴来增强可爱性
    红毛类型
    oracle学习总结4
    对springMVC的简单理解
    理解RESTful架构
    项目移植过程中报:“Project facet Java version 1.7 is not supported.” 错误
    svn服务器的搭建
    oracle学习总结3
  • 原文地址:https://www.cnblogs.com/lvdongjie/p/4490115.html
Copyright © 2020-2023  润新知