gpt4 book ai didi

c预处理器将多个参数作为一个参数传递

转载 作者:太空狗 更新时间:2023-10-29 16:41:21 25 4
gpt4 key购买 nike

C 预处理器正在传递多个参数,就好像它们是单个参数一样。我很确定问题出在我们如何调用 untouchable 宏,但是我们为更改 first 宏所做的每一次尝试都未能产生预期的结果。这是一个完整的代码示例,其中包含解释发生了什么以及我们想要发生什么的注释:

//this can be changed, but it must remain a #define to be of any use to us
#define first a,b,c

// v all code below this line cannot be altered (it's outside of our control)

#define untouchable(name, c1, c2, c3) \
wchar_t name[] = \
{ \
quote(c1), \
quote(c2), \
quote(c3) \
}

#define quote(c) L#@c

// ^ all code above this line cannot be altered (it's outside of our control)

int _tmain(int argc, _TCHAR* argv[])
{
static untouchable(mrNess, first);

// the line above is precompiled to:
// static wchar_t mrNess[] = { L'a,b,c', L, L };

// whereas we want:
// static wchar_t mrNess[] = { L'a', L'b', L'c' };

return 0;
}

我们在 Windows 下的 VisualStudio 下编译。

最佳答案

当预处理器遇到类函数宏的调用时,它首先识别参数,接下来完全宏展开它们*,最后用它的替换列表替换宏调用,用在适当的地方插入扩展参数。宏 first 的扩展执行(或将执行)太晚,预处理器无法在扩展中识别宏 untouchable() 的单独参数。您需要找到另一种方法。

一种可能性是插入一个间接级别:

#define untouch_wrap(name, args) untouchable(name, args)

static untouch_wrap(mrNess, first);

在那里,firstuntouch_wrap 之前展开,这样当结果被重新扫描以替换更多的宏时,untouchable() 的结果调用 具有正确数量的参数。

这确实依赖于 untouch_wrap() 的第二个参数来扩展为由三个成员组成的以逗号分隔的列表。像这样定义 untouch_wrap() 会更简洁、更灵活:

#define untouch_wrap(name, ...) untouchable(name, __VA_ARGS__)

...但是 MSVC 对可变参数宏的处理是不符合规范的,我怀疑它会因此而绊倒。


* 对于作为预处理器字符串化 (#) 和标记粘贴 (##) 运算符的操作数的参数,扩展被抑制。

关于c预处理器将多个参数作为一个参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38337666/

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