C11 variadic宏:将元素放入方括号中
我正在看一个宏,或更可能是宏的组合,这将达到以下效果:
BRACKET(a) => { a }
BRACKET(a, b) => { a }, { b }
BRACKET(a, b, c) => { a }, { b }, { c }
听起来很简单吗? las,我找不到任何合理的解决方案。 基于计算论点的NB,然后为每个可能的参数创建一个专门的宏观,可能会有一些重量级的宏观,这对手头上的问题感到严重夸张(并且很难为可怜的继任者维持)。但是到目前为止,我找不到任何简单的解决方案。
编辑: 当前的解决方案我们正在尝试改进: 每个列表大小使用一个宏。
BRACKET1(a) => { a }
BRACKET2(a, b) => { a }, { b }
BRACKET3(a, b, c) => { a }, { b }, { c }
etc.
I'm looking at a macro, or more likely a combination of macros, that would achieve the following effect :
BRACKET(a) => { a }
BRACKET(a, b) => { a }, { b }
BRACKET(a, b, c) => { a }, { b }, { c }
Sounds pretty simple ?
Alas, I couldn't find any reasonable solution.
There are possible heavyweight ones, based on counting the nb of arguments, and then creating one dedicated macro for each possible nb of arguments, which felt seriously overkill for the problem at hand (and hard to maintain for the poor successor). But I couldn't find any simpler solution so far.
Edit :
Current solution we are trying to improve upon :
Uses one macro per list size.
BRACKET1(a) => { a }
BRACKET2(a, b) => { a }, { b }
BRACKET3(a, b, c) => { a }, { b }, { c }
etc.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
variadic宏很少很容易用于通用编程目的。您可以通过一些非常复杂的方法将它们扩展到一定的固定最大量,但是最好选择替代解决方案。特别是如果您冒着发明一些特定项目的宏观语言的风险。
这样的替代解决方案是迫使呼叫者使用特定的变异数据集,而不是对某些功能样宏的变异输入。
例如,如果呼叫者可以通过“ X-MaCro”定义任何长度和内容的数据集:
那么我们可以将所有特定行为应用于该数据集,例如:
它将扩展到
{1} ,{2},{3},{4},{5},
。使用此方法,您可以创建各种类似宏的方式:
#define逗号(x)x,
- >1,2,3,4,5,
#define str_literal(x)#x
- >“ 1”“ 2”“ 3”“ 4”“ 5”
- >“ 12345”
或您喜欢的任何东西。
Variadic macros can rarely be easily used for generic programming purposes. There are some quite complex ways you could expand them up to a certain fixed maximum amount, but it might be better to look for alternative solutions instead. Especially in case you are risking to invent some project-specific macro language.
One such alternative solution would be to force the caller to work with specific variadic data sets instead of variadic inputs to some function-like macro.
For example if the caller can define a data set of any length and content through an "X-macro":
Then we can apply all manner of specific behavior to that data set, for example:
Which will expand to
{1},{2},{3},{4},{5},
.With this method you can create all manner of similar macros:
#define COMMAS(x) x,
->1,2,3,4,5,
#define STR_LITERAL(x) #x
->"1" "2" "3" "4" "5"
->"12345"
Or whatever you fancy.