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
Linda HamiltonOriginal
2024-12-17 06:29:25915browse

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

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 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!

Statement:
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