Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using commas inside a macro without parenthesis: How can I mix and match with a template?

Tags:

c++

macros

Consider a simple macro:

#define ECHO(x) x

ECHO(foo(1, 2))

This produces the exact output we expect:

foo(1, 2)

The above example works because the parenthesis adjacent to the function call are recognized by the preprocessor.

Now consider what happens if I use a template instead of a function call:

ECHO(template<int, bool>)

This causes an error because the preprocessor interprets the template<int and the bool> as two separate arguments to the macro. The preprocessor doesn't recognize <> for scope!

Is there anyway to use a template like this in a macro?

like image 450
chrisaycock Avatar asked Feb 23 '12 16:02

chrisaycock


People also ask

Can a template be considered as a macro?

Macro vs Template Macro are used in C and C++ for replacement of numbers, small inline functions etc. Template is only available in C++ language. It is used to write small macro like functions etc.

Where is __ Va_args __ defined?

The C standard mandates that the only place the identifier __VA_ARGS__ can appear is in the replacement list of a variadic macro. It may not be used as a macro name, macro argument name, or within a different type of macro. It may also be forbidden in open text; the standard is ambiguous.

Which of the following is the proper syntax for declaring macros in C?

Macros using #define A macro is a fragment of code that is given a name. You can define a macro in C using the #define preprocessor directive.

What is a macro argument?

Macro Arguments (DEFINE-! ENDDEFINE command) The macro definition can include macro arguments, which can be assigned specific values in the macro call. There are two types of arguments: keyword and positional. Keyword arguments are assigned names in the macro definition; in the macro call, they are identified by name.


2 Answers

#define COMMA ,
ECHO(template<int COMMA bool>)

A little painful, but it works.

FWIW, if the syntax for the argument allows ()s, you don't need the substitution, e.g.,

ECHO((a, b))

will work for a single argument macro but that doesn't work in all cases (including yours).

like image 64
smparkes Avatar answered Oct 16 '22 17:10

smparkes


A variadic macro may help:

#define ECHO(x...) x

ECHO(foo(1, 2))
ECHO(template<int, bool>)
like image 45
Yan Avatar answered Oct 16 '22 17:10

Yan