如何展开宏并删除逗号 [英] How to expand macro and delete comma

查看:117
本文介绍了如何展开宏并删除逗号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我想编写自己的printf()替代方法,但必须对变量参数执行计算:

For example I want to write my own printf() alternative, but I have to perform calculations on the variable arguments:

#define log(fmt_string, ...) my_log(fmt_string, pack_args(__VA_ARGS__), __VA_ARGS__)

其中pack_args(...)-也是一个宏. 我应该如何更改此代码以处理唯一的fmt_string存在情况?

where pack_args(...) - is a macro too. How should I change this code to handle the only fmt_string presence scenario?

log("Some message here");

推荐答案

P99 中,我有两个宏

#define P00_ARG(                                               \
 _1, _2, _3, _4, _5, _6, _7, _8,                               \
 _9, _10, _11, _12, _13, _14, _15, _16,                        \
  ... etc ...                                                  \
 _153, _154, _155, _156, _157, _158, _159,                     \
 ...) _159
#define P99_HAS_COMMA(...) P00_ARG(__VA_ARGS__,                \
 1, 1, 1, 1, 1, 1, 1,                                          \
 1, 1, 1, 1, 1, 1, 1, 1,                                       \
  ... etc ....                                                 \
 1, 1, 1, 1, 1, 1, 0, 0)

您可以使用它来确定您的参数是否带有逗号(因此,参数多于格式)或没有(仅格式).然后,您可以使用它来构造对两个宏之一的调用:

You can use this to determine if your argument has a comma (so there are more arguments than your format) or not (only a format). You can then use that to construct a call to one of two macros:

#define log(...) log2(P99_HAS_COMMA(__VA_ARGS__), __VA_ARGS__)
#define log2(N, ...) log3(N, __VA_ARGS__)
#define log3(N, ...) log ## N(__VA_ARGS__)

#define log0(FMT)              /* your version with format only goes here */
#define log1(FMT, __VA_ARGS__) /* your version with more goes here */

这篇关于如何展开宏并删除逗号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆