简体   繁体   English

向variadic宏添加默认参数

[英]Adding default arguments to variadic macro

Is it possible to add default arguments before variable argument in variadic macro? 是否有可能在可变参数宏中的变量参数之前添加默认参数? eg I have the version of macro something like 例如,我有像宏的版本

#define MACRO(arg1, ...) func(arg1, ##__VA_ARGS__)

I would like to add 2 more default arguments in the macro before variable arguments so that it should not affect previous version. 我想在变量参数之前在宏中添加另外2个默认参数,这样它就不会影响以前的版本。 Like: 喜欢:

#define MACRO(arg1, arg2 = "", arg3 = "", ...) func(arg1, arg2, arg3, ##__VA_ARGS__)

Any help would be appreciated. 任何帮助,将不胜感激。

What you can do: 你可以做什么:

struct foo {
    int   aaa;
    char  bbb;
    char  *ccc;
};

#define BAR(...)   bar((struct foo){__VA_ARGS__})

void bar(struct foo baz)
    /* set defaults */
    if (!baz.aaa)
        baz.aaa = 10;
    if (!baz.bbb)
        baz.bbb = 'z';
    if (!baz.ccc)
        baz.ccc = "default";

    printf("%d, %c, %s\n", baz.aaa, baz.bbb, baz.ccc);
}

...
BAR();                     // prints "10, z, default"
BAR(5);                    // prints "5, z, default"
BAR(5,'b');                // prints "5, b, default"
BAR(5, 'b', "something");  // prints "5, b, something"

Bad thing about this - zero parameter is treated like no parameter, eg BAR(0, 'c') will produce string 10, c, default 关于这一点的坏事 - 零参数被视为没有参数,例如BAR(0, 'c')将产生字符串10, c, default

I do not think this is possible. 我不认为这是可能的。 How would the compiler/preprocessor knows if the second and third arguments are part of the variable arguments or override the default values ? 如果第二个和第三个参数是变量参数的一部分还是覆盖默认值,编译器/预处理器将如何知道? That's the reason why parameters with default values have to be in last position in a function. 这就是为什么具有默认值的参数必须位于函数中的最后位置的原因。

I'm afraid you'll have to have two macros or three if you to be able to specify arg2 and use arg3 default value, but this is error-prone. 如果你能够指定arg2并使用arg3默认值,我担心你必须有两个宏或三个宏,但这很容易出错。

#define MACRO(arg1, ...) func(arg1, "", "", ##__VA_ARGS__)
#define MACRO2(arg1, arg2, ...) func(arg1, arg2, "", ##__VA_ARGS__)
#define MACRO3(arg1, arg2, arg3, ...) func(arg1, arg2, arg3, ##__VA_ARGS__)

Not as an answer to your question but as a way to simply solve your problem: 不是作为您问题的答案,而是作为简单解决问题的方法:

#define MACRO(arg1, ...)          \
    /* pre-treatment */           \
    func(arg1, ##__VA_ARGS__)     \
    /* post-treatment */          \

void func (type1 arg1, type2 arg2 = "", type3 arg3 = "", ...);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM