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

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

Linda Hamilton
Release: 2024-12-11 06:45:09
Original
761 people have browsed it

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

Comma in C/C Macros

In C/C macros, it is often necessary to separate multiple arguments with commas. However, issues arise when the macro expects a specific number of arguments, and providing more or less causes errors.

Problem Scenario

Consider a macro defined as follows:

#define FOO(type, name) type name
Copy after login

While this macro can be used simply, e.g.:

FOO(int, int_var);
Copy after login

It becomes problematic when complex types are involved:

FOO(std::map<int, int>, map_var); // error: macro "FOO" passed 3 arguments, but takes just 2
Copy after login

Traditional Solution

One common approach is to create a new type alias and use it within the macro:

typedef std::map<int, int> map_int_int_t;
FOO(map_int_int_t, map_var); // OK
Copy after login

Macro-Based Solution

Alternatively, you can define a macro representing a comma:

#define COMMA ,
Copy after login

Using this macro, you can now pass complex types without errors:

FOO(std::map<int COMMA int>, map_var);
Copy after login

Additional Use Case

This approach also proves useful when stringifying macro arguments, as illustrated below:

#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 print:
std::map has typeid name "St3mapIiiSt4lessIiESaISt4pairIKiiEEE"

The above is the detailed content of How Can I Handle Commas in Complex C/C Macro 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