Home > Backend Development > C++ > How Can I Handle Commas in Macro Arguments in C/C ?

How Can I Handle Commas in Macro Arguments in C/C ?

Linda Hamilton
Release: 2024-12-17 06:29:25
Original
909 people have browsed it

How Can I Handle Commas in Macro Arguments in C/C  ?

Commas within Macros 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
Copy after login

While it is straightforward to use the macro with arguments like:

FOO(int, int_var);
Copy after login

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
Copy after login

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
Copy after login

However, this approach lacks ergonomics and requires additional type conversions.

An alternative solution involves defining a macro named COMMA:

#define COMMA ,
Copy after login

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);
Copy after login

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);
}
Copy after login

This code will output: "std::map has typeid name "St3mapIiiSt4lessIiESaISt4pairIKiiEEE"."

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template