我有
#define A_T 1 #define B_T 2 int x_a = 1, x_b =2;如何定义一个宏,它可以将后缀_a和_b连接到var名称?
for example, something like this #define A_T_SUF _a #define B_t_SUF _b #define SUFFIX(t) t ## _SUF #define VAR_SUF(var, t) var ## SUFFIX(t) ..... VAR_SUF(x, A_T) ---> be replaced to x_a这可能吗?
I have
#define A_T 1 #define B_T 2 int x_a = 1, x_b =2;How can I define a macro, which can concatenate the suffix _a and _b to the var name?
for example, something like this #define A_T_SUF _a #define B_t_SUF _b #define SUFFIX(t) t ## _SUF #define VAR_SUF(var, t) var ## SUFFIX(t) ..... VAR_SUF(x, A_T) ---> be replaced to x_aIs this possible?
最满意答案
您需要VAR_SUF宏中的额外间接,以强制它在连接令牌之前评估被调用的宏,而不是先连接:
#define A_T_SUF _a #define B_t_SUF _b #define SUFFIX(t) t ## _SUF #define CAT(a, b) a ## b #define XCAT(a, b) CAT(a, b) #define VAR_SUF(var, t) XCAT(var, SUFFIX(t)) ..... VAR_SUF(x, A_T) ---> be replaced to x_a没有额外的间接, VAR_SUF(x, A_T)将扩展为xSUFFIX(A_T) (首先连接,然后寻找更多的宏)。 使用额外的CAT / XCAT间接,它将首先扩展SUFFIX(A_T)然后连接。
XCAT是EXPAND_AND_CONCATENATE ,而CAT只是CONCATENATE (没有扩展。)
编辑
如果A_T也是一个宏(例如,# #define A_T 1 ),那么它将首先被替换。 您可以通过删除SUFFIX宏中的##的间接来避免这种情况:
#define A_T_SUF _a #define B_t_SUF _b #define CAT(a, b) a ## b #define XCAT(a, b) CAT(a, b) #define VAR_SUF(var, t) XCAT(var, t##_SUF) ..... VAR_SUF(x, A_T) ---> be replaced to x_a这将导致首先发生连接,然后扩展宏,然后将发生其他连接
如果x也是一个宏,那么你有一个问题,因为在连接它们之前没有好的方法来扩展一个令牌而不是另一个令牌。
You need an extra indirection in the VAR_SUF macro to force it to evaluate the called macros before concatenating the tokens instead of concatenating first:
#define A_T_SUF _a #define B_t_SUF _b #define SUFFIX(t) t ## _SUF #define CAT(a, b) a ## b #define XCAT(a, b) CAT(a, b) #define VAR_SUF(var, t) XCAT(var, SUFFIX(t)) ..... VAR_SUF(x, A_T) ---> be replaced to x_awithout the extra indirect, VAR_SUF(x, A_T) would expand to xSUFFIX(A_T) (concatenate first, then look for more macros). With the extra CAT/XCAT indirection, it will expand SUFFIX(A_T) first and then concatenate.
XCAT is short for EXPAND_AND_CONCATENATE, while CAT is just CONCATENATE (without expansion.)
edit
If A_T is also a macro (eg, #define A_T 1) then it will be replaced first. You can avoid that by removing the indirection of the ## in the SUFFIX macro:
#define A_T_SUF _a #define B_t_SUF _b #define CAT(a, b) a ## b #define XCAT(a, b) CAT(a, b) #define VAR_SUF(var, t) XCAT(var, t##_SUF) ..... VAR_SUF(x, A_T) ---> be replaced to x_aThis will cause that concatenation to happen first, then macros will be expanded, then the other concatenation will happen
If x is also a macro, then you have a problem, as there's no good way to expand one token and not the other before you concatenate them.
更多推荐
发布评论