In C/C , macros are often used to simplify and generalize code. However, when macros take multiple arguments, it can be difficult to handle commas correctly.
Consider the following macro:
#define FOO(type, name) type name
This macro can be used to declare a variable of a specific type, for example:
FOO(int, int_var);
However, if the type contains commas, such as in a template template parameter, the macro fails. For instance:
FOO(std::map<int, int>, map_var); // error: macro "FOO" passed 3 arguments, but takes just 2
To resolve this issue, one option is to introduce a typedef:
typedef std::map<int, int> map_int_int_t; FOO(map_int_int_t, map_var); // OK
While this approach works, it can be cumbersome and introduce type compatibility issues.
An alternative solution is to use the preprocessor's COMMA macro:
#define COMMA , FOO(std::map<int COMMA int>, map_var);
This allows commas to be included in macro arguments without causing errors. Additionally, it can be used for splicing macro arguments into strings:
#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 prints:
std::map<int , int> has typeid name "St3mapIiiSt4lessIiESaISt4pairIKiiEEE"
By utilizing the COMMA macro, developers can avoid typedefs and ensure that commas are handled correctly in macros.
The above is the detailed content of How Can I Handle Commas Correctly in C/C Macros with Multiple Arguments?. For more information, please follow other related articles on the PHP Chinese website!