gpt4 book ai didi

C 宏 : How to use macro to generate parameters list of another macro

转载 作者:太空宇宙 更新时间:2023-11-04 08:08:47 25 4
gpt4 key购买 nike

我有很多行代码如下:

     sp_setup_point( setup, get_vert(vertex_buffer, i-0, stride) );

对于它们中的每一个,我都希望能够提取 (i-0) 并将其传递给另一个函数。喜欢:

     sp_setup_point( setup, get_vert(vertex_buffer, i-0, stride) );
my_test_func(i-0);

所以我写了两个宏:

      #define GET_VERT(_x, _y, _z) get_vert(_x, _y, _z) , _y
#define SP_SETUP_POINT(_x, _y, _z) sp_setup_point(_x, _y); my_test_func(_z);

并这样称呼他们:

     SP_SETUP_POINT( setup, GET_VERT(vertex_buffer, i-0, stride));

然而,它没有给出我想要的,它扩展为:

     sp_setup_point(setup, get_vert(vertex_buffer, i-0, stride), i-0); my_test_func();

和 MSVC 编译器提示

    not enough actual parameters for macro 'SP_SETUP_POINT'

根据https://gcc.gnu.org/onlinedocs/cpp/Argument-Prescan.html,我搜索了很多

Macro arguments are completely macro-expanded before they are substituted into a macro body, unless they are stringified or pasted with other tokens. After substitution, the entire macro body, including the substituted arguments, is scanned again for macros to be expanded. The result is that the arguments are scanned twice to expand macro calls in them

参数已完全扩展,但无法识别附加参数。怎么回事?任何建议表示赞赏。

最佳答案

原因,IIRC,是实际参数列表的 GET_VERT inside 仅在扫描封闭宏调用后 才展开。所以PP首先要看SP_SETUP_POINT的参数列表末尾的“)”。在此过程中,它认识到它是声明形式的一个参数。一级间接有帮助,但要注意,C 中的宏编程很奇怪,并且由于早期的错误实现选择而受到影响,由于大量的兼容性债务,没有人敢于纠正这些选择。

#define GET_VERT(_x, _y, _z) get_vert(_x, _y, _z) , _y
#define SP_SETUP_POINT(_x, expandme) SP_SETUP_POINT_(_x,expandme)
#define SP_SETUP_POINT_(_x,_y,_z) sp_setup_point(_x, _y); my_test_func(_z)

最后一种形式最好写成

#define SP_SETUP_POINT_(_x,_y,_z) do{ sp_setup_point(_x, _y); my_test_func(_z); }while(0)

因为写 sg.喜欢

if (a==1) SP_SETUP_POINT(setup, GET_VERT(vertex_buffer, i-0, stride));

将导致控制流中的不可见错误。

关于C 宏 : How to use macro to generate parameters list of another macro,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40928439/

25 4 0