如何重新定义带有减少参数的C++宏?

huangapple go评论56阅读模式
英文:

How to redefine c++ macro with reduced parameters?

问题

我在现有项目中有以下宏:

    #define TRACE1(attr, str,...)   REL_LOG(attr, str, ##_VA_ARGS__)
    #define TRACE2(str,...)       REL_LOG(str, ##_VA_ARGS__)

它们被使用如下:

    TRACE1(1, "hello %s", "world");
    TRACE2("[prefix] hello %s", "world");

现在我需要将TRACE1宏转换为TRACE2宏,以避免使用attr参数。我不想修改所有调用TRACE1的地方。我尝试了以下操作:

    #undef TRACE1
    #define TRACE1(str, ...) TRACE2(str, ...)

然而,得到以下编译错误,// 在第二行

> 错误:在 '...' 标记之前预期主表达式
英文:

I have following macros in an existing project,

#define TRACE1(attr,str,...)   REL_LOG(attr, str, ##_VA_ARGS__)
#define TRACE2(str,...)       REL_LOG(str, ##_VA_ARGS__)

And they have been used like,

TRACE1(1, "hello %s", "world");
TRACE2("[prefix] hello %s", "world");

Now I need to transform the TRACE1 macro to TRACE2 macro so that attr param will be avoided. I dont want to touch all the places where TRACE1 has been called for purpose. I did something like,

#undef TRACE1
#define TRACE1(str, ...) TRACE2(str,...)

However, getting following compiler error, // in second line

> error: expected primary-expression before '...' token

答案1

得分: 3

你只能将 ... 作为参数,在相关文本中,必须使用 __VA_ARGS__ 表示未定义数量的参数值。你可以这样做:

#define TRACE1(str, ...) TRACE2(str, __VA_ARGS__)  // 调用 TRACE2 完成相同的操作
// 或者简单地
#define TRACE1 TRACE2  // TRACE1 等同于 TRACE2
// 但为了保持 TRACE1 的相同语法,忽略第一个参数,它应该是这样的
#define TRACE1(dummy, str, ...) TRACE2(str, __VA_ARGS__)
英文:

You can only have ... as parameter, in the associated text you must use __VA_ARGS__ to represent undefined number of parameter values. You can do:

#define TRACE1(str, ...) TRACE2(str,__VA_ARGS__)  // call TRACE2 to do the same
// or simply
#define TRACE1  TRACE2                          // TRACE1 is TRACE2
// but to keep TRACE1 same syntax ignoring the 1st parameter it is
#define TRACE1(dummy,str, ...) TRACE2(str,__VA_ARGS__)

huangapple
  • 本文由 发表于 2023年3月31日 20:35:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/75898589.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定