'C11 variadic macro : put elements into brackets [duplicate]
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.
Solution 1:[1]
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":
#define DATA(X) X(1) X(2) X(3) X(4) X(5)
Then we can apply all manner of specific behavior to that data set, for example:
#define BRACKET(x) {x},
...
DATA(BRACKET);
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Lundin |