Home > Backend Development > C++ > How Can I Handle Commas Correctly in C/C Macros with Multiple Arguments?

How Can I Handle Commas Correctly in C/C Macros with Multiple Arguments?

Patricia Arquette
Release: 2024-12-11 16:19:20
Original
317 people have browsed it

How Can I Handle Commas Correctly in C/C   Macros with Multiple Arguments?

Macros and Commas in C/C

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

This macro can be used to declare a variable of a specific type, for example:

FOO(int, int_var);
Copy after login

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

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

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

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

This code prints:

std::map<int , int> has typeid name "St3mapIiiSt4lessIiESaISt4pairIKiiEEE"
Copy after login

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!

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