Comma in C/C Macros
In C/C macros, it is often necessary to separate multiple arguments with commas. However, issues arise when the macro expects a specific number of arguments, and providing more or less causes errors.
Problem Scenario
Consider a macro defined as follows:
#define FOO(type, name) type name
While this macro can be used simply, e.g.:
FOO(int, int_var);
It becomes problematic when complex types are involved:
FOO(std::map<int, int>, map_var); // error: macro "FOO" passed 3 arguments, but takes just 2
Traditional Solution
One common approach is to create a new type alias and use it within the macro:
typedef std::map<int, int> map_int_int_t; FOO(map_int_int_t, map_var); // OK
Macro-Based Solution
Alternatively, you can define a macro representing a comma:
#define COMMA ,
Using this macro, you can now pass complex types without errors:
FOO(std::map<int COMMA int>, map_var);
Additional Use Case
This approach also proves useful when stringifying macro arguments, as illustrated below:
#include <cstdio> #include <map> #include <typeinfo> #define STRV(...) #__VA_ARGS__ #define COMMA , #define FOO(type, bar) bar(STRV(type) \ " has typeid name \"%s\"", typeid(type).name()) int main() { FOO(std::map<int COMMA int>, std::printf); }
This code will print:
std::map
The above is the detailed content of How Can I Handle Commas in Complex C/C Macro Arguments?. For more information, please follow other related articles on the PHP Chinese website!