【问题标题】:__VA_ARGS__ Macro expansion__VA_ARGS__ 宏扩展
【发布时间】:2012-08-01 06:09:19
【问题描述】:

我试图让我的宏像NSLog() 一样工作,它接受可变参数。下面的代码会导致解析问题。

定义这个的正确方法是什么?

#define TF_CHECKPOINT(f, ...) \
do { \
NSString *s = [[NSString alloc] initWithFormat:f arguments:__VA_ARGS__] autorelease]; \
[TestFlight passCheckpoint:[NSString stringWithFormat:@"%@: %@", [self class], s]]; \
} while (0)

【问题讨论】:

  • 我不确定你的意思是什么变量参数,因为__VA_ARGS__ 已经代表宏的变量参数,所以你可以像使用下面的宏一样使用NSLog(...) 通常是:#define AnotherLog(...) NSLog(__VA_ARGS__),在它之后,它将是源代码中的有效行:`AnotherLog(@"%d, %@", 1, @"text");你的最终目标到底是什么?

标签: objective-c macros variadic-functions


【解决方案1】:

您忘记了autorelease 消息的左括号。

此外,-[NSString initWithFormat:arguments:] 需要 va_list 参数,而 __VA_ARGS__ 被所有传递的参数替换。在这里,您需要使用-[NSString initWithFormat:]+[NSString stringWithFormat:]

最后,您可以在__VA_ARGS__ 前加上##。这样,在没有参数的情况下,前面的逗号就会被删除。

试试这个:

#define TF_CHECKPOINT(f, ...) \
do { \
NSString *s = [NSString stringWithFormat:(f), ##__VA_ARGS__]; \
[TestFlight passCheckpoint:[NSString stringWithFormat:@"%@: %@", [self class], s]]; \
} while (0)

【讨论】:

  • 好吧,这是我的愚蠢错误,因为我忘记了左括号。
猜你喜欢
  • 1970-01-01
  • 2021-09-09
  • 1970-01-01
  • 2015-11-30
  • 1970-01-01
  • 2011-07-05
  • 2021-05-23
  • 1970-01-01
相关资源
最近更新 更多