Home >Backend Development >C++ >How Can I Handle Commas in Macro Arguments in C/C ?
One may encounter difficulties when utilizing macros that accept multiple arguments, especially when the arguments contain commas. Consider the following example:
#define FOO(type, name) type name
While it is straightforward to use the macro with arguments like:
FOO(int, int_var);
Issues arise when dealing with complex arguments involving commas, such as:
FOO(std::map<int, int>, map_var); // Error: 3 arguments passed to macro 'FOO', which takes only 2
To address this, one could introduce a custom type definition:
typedef std::map<int, int> map_int_int_t; FOO(map_int_int_t, map_var); // Compiles successfully
However, this approach lacks ergonomics and requires additional type conversions.
An alternative solution involves defining a macro named COMMA:
#define COMMA ,
With this definition, complex arguments can be passed to the macro using the COMMA macro, for example:
FOO(std::map<int COMMA int>, map_var);
This method also allows for argument stringification, as illustrated in the following code:
#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 output: "std::map
The above is the detailed content of How Can I Handle Commas in Macro Arguments in C/C ?. For more information, please follow other related articles on the PHP Chinese website!