gpt4 book ai didi

c++ - 如何通过#define 函数将参数添加到格式化字符串函数调用

转载 作者:搜寻专家 更新时间:2023-10-31 01:21:38 24 4
gpt4 key购买 nike

我想创建将参数插入函数调用的宏。例如,我在下面声明了函数 Action()。 Action 在输入时采用状态编号的枚举和带有可选参数的格式化字符串。

我想定义宏,而不是调用 Action( ActionState1, "someText %d", &arg)ActionState1 作为状态参数,我可以调用State1("someText %d", &arg) 代替。这样,宏就会为我的状态参数保留在 ActionState1 中。我正在考虑以下内容:

#define State1(formatedString, ...) Action(ActionState1, formatedString, ...)
#define State2(formatedString, ...) Action(ActionState2, formatedString, ...)
#define State3(formatedString, ...) Action(ActionState3, formatedString, ...)

enum {
ActionState1,
ActionState2,
ActionState3
}

static void Action( State state, String formatedString, ...);

有谁知道正确的格式是什么?

最佳答案

我相信__VA_ARGS__是你要找的:

#define State1(formattedString, ...) Action(1, (formattedString), __VA_ARGS__)
.
.
.

这是一个 C99 特性,Wikipedia claims它们不是任何官方 C++ 标准的一部分(我注意到这一点是因为您使用了 C++ 标记),而是一个相当流行的扩展。在 this question 上有一些很好的讨论.

关于c++ - 如何通过#define 函数将参数添加到格式化字符串函数调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3663709/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com