可变参数宏中标记的串联 [英] Concatenation of tokens in variadic macros

查看:61
本文介绍了可变参数宏中标记的串联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C语言中,是否可以将一个可变参数的每个变量参数连接起来?

In C, is it possible to concatenate each of the variable arguments in a a variadic macro?

示例:

MY_MACRO(A, B, C) // will yield HDR_A, HDR_B, HDR_C
MY_MACRO(X, Y)    // will yield HDR_X, HDR_Y

普通的##运算符对于可变参数宏有特殊的含义(避免空参数列表使用逗号).与__VA_ARGS__一起使用时,串联仅与第一个标记一起发生.

The normal ## operator has special meaning for variadic macros (avoiding the comma for empty argument list). And concatenation when used with __VA_ARGS__ takes place with the first token only.

示例:

#define MY_MACRO(...) HDR_ ## __VA_ARGS__

MY_MACRO(X, Y)    // yields HDR_X, Y

建议?

推荐答案

首先,您提到的逗号规则是gcc扩展,标准C没有它,而且很可能永远也不会,因为可以实现该功能通过不同的方式.

First, the comma rule you are mentioning is a gcc extension, standard C doesn't have it and most probably will never have it since the feature can be achieved by different means.

您正在寻找的是带有宏的元编程,这是可能的,但是您需要一些技巧来实现. P99 为您提供了以下工具:

What you are looking for is meta programming with macros, which is possible, but you'd need some tricks to achieve that. P99 provides you with tools for that:

#define MY_PREFIX(NAME, X, I) P99_PASTE2(NAME, X)
#define MY_MACRO(...) P99_FOR(HDR_, P99_NARG(__VA_ARGS__), P00_SEQ, MY_PREFIX, __VA_ARGS__)

  • 此处MY_PREFIX描述了个人必须执行的操作 项目.
  • P00_SEQ声明如何分隔项目
  • P99_NARGS只是计算参数的数量
    • Here MY_PREFIX describes what has to be done with the individual items.
    • P00_SEQ declares how the items should be separated
    • P99_NARGS just counts the number of arguments
    • 这篇关于可变参数宏中标记的串联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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