连接X宏的多个标记 [英] Concatenate multiple tokens for X macro

查看:68
本文介绍了连接X宏的多个标记的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试同时使用X宏和预处理程序级联。

I'm trying to use X macros and preprocessor concatenation, both for the first time, together.

我已经阅读了很多关于SO的其他问题与预处理器级联有关,但仍无法解决问题或如何适应我的用例。

I've read a lot of the other questions on SO related to preprocessor concatenation but not yet been able to wrap my head around them or how to adapt those to my use case.

项目列表是ID号列表一堆结构,例如:

The list of items is a list of ID numbers for a bunch of structs, like so:

#define LIST_OF_ID_NUMS \
    X(1) \
    X(2) \
    X(3) \
    X(4) \
    X(5) \
    X(6) \
    X(7) \
    X(8) \
    X(9) \
    X(10) \
    X(11)

我可以这样声明结构:

#define X(id_num) static myFooStruct foo_## id_num ;
LIST_OF_ID_NUMS 
#undef X
// gives: 'struct myFooStruct foo_n;' where 'n' is an ID number

现在我也想将每个结构的成员之一初始化为等于ID号,这样 foo_n.id = n; 。通过使用以下命令,我已经能够实现第一个令牌连接:

Now I would also like to initialise one of the members of each struct to be equal to the ID number, such that foo_n.id = n;. I have been able to achieve the first token concatenation, by using the following:

#define X(id_num) foo_## id_num .id = 3 ;
LIST_OF_ID_NUMS 
#undef X
// gives: 'foo_n.id = x' where 'x' is some constant (3 in this case)

但是我无法理解如何进一步正确地扩展该想法,以便也替换分配的值。我试过了:

But I have not been able to understand how to correctly expand the idea further so that the assigned value is also replaced. I have tried:

#define X(id_num) foo_## id_num .id = ## id_num ;
LIST_OF_ID_NUMS 
#undef X
// Does NOT give: 'foo_n.id = n;' :(

以及使用双间接连接进行连接的各种尝试,但均未成功,上述尝试导致 LIST_OF_ID_NUMS

And various attempts at using double indirection for the concatenation. But have not been successful. The above attempt resulting in errors like the following for each item in the LIST_OF_ID_NUMS:

foo.c:47:40: error: pasting "=" and "1" does not give a valid preprocessing token
  #define X(id_num) foo_## id_num .id = ## id_num ;
                                    ^
foo.c:10:5: note: in expansion of macro 'X'
  X(1) \
  ^
foo.c:48:2: note: in expansion of macro 'LIST_OF_ID_NUMS '
  LIST_OF_ID_NUMS 

如何最好地实现 foo_n.id = n 的形式?

How can I best achieve the form foo_n.id = n?

推荐答案

据我所知,这应该只是:

As far as I can tell, that should simply be :

#define X(id_num) foo_## id_num .id = id_num ;

这篇关于连接X宏的多个标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆